Instruction stringlengths 45 106 | input_code stringlengths 1 13.7k | output_code stringlengths 1 13.7k |
|---|---|---|
Produce a functionally identical Go code for the snippet given in Lua. | function split(line)
local wa = {}
for i in string.gmatch(line, "%S+") do
table.insert(wa, i)
end
return wa
end
local file = assert(io.open("days_of_week.txt", "r"))
io.input(file)
local line_num = 0
while true do
local line = io.read()
if line == nil then break end
line_num = line_num + 1
if string.len(line) > 0 then
local days = split(line)
if #days ~= 7 then
error("There aren't 7 days in line "..line_num)
end
local temp = {}
for i,day in pairs(days) do
if temp[day] ~= nil then
io.stderr:write(" β "..line.."\n")
else
temp[day] = true
end
end
local length = 1
while length < 50 do
temp = {}
local count = 0
for i,day in pairs(days) do
local key = string.sub(day, 0, length)
if temp[key] ~= nil then break end
temp[key] = true
count = count + 1
end
if count == 7 then
print(string.format("%2d %s", length, line))
break
end
length = length + 1
end
end
end
| package main
import(
"bufio"
"fmt"
"os"
"strings"
)
func distinctStrings(strs []string) []string {
len := len(strs)
set := make(map[string]bool, len)
distinct := make([]string, 0, len)
for _, str := range strs {
if !set[str] {
distinct = append(distinct, str)
set[str] = true
}
}
return distinct
}
func takeRunes(s string, n int) string {
i := 0
for j := range s {
if i == n {
return s[:j]
}
i++
}
return s
}
func main() {
file, err := os.Open("days_of_week.txt")
if err != nil {
fmt.Println("Unable to open file.")
return
}
defer file.Close()
reader := bufio.NewReader(file)
lineCount := 0
for {
line, err := reader.ReadString('\n')
if err != nil {
return
}
line = strings.TrimSpace(line)
lineCount++
if line == "" {
fmt.Println()
continue
}
days := strings.Fields(line)
daysLen := len(days)
if (len(days) != 7) {
fmt.Println("There aren't 7 days in line", lineCount)
return
}
if len(distinctStrings(days)) != 7 {
fmt.Println(" β ", line)
continue
}
for abbrevLen := 1; ; abbrevLen++ {
abbrevs := make([]string, daysLen)
for i := 0; i < daysLen; i++ {
abbrevs[i] = takeRunes(days[i], abbrevLen)
}
if len(distinctStrings(abbrevs)) == 7 {
fmt.Printf("%2d %s\n", abbrevLen, line)
break
}
}
}
}
|
Generate an equivalent C version of this Mathematica code. |
Abbreviations[maxLength_Integer][str_String]:=Array[StringTake[StringPadRight[str,maxLength,"_"],#]&,maxLength];
ShortestUniqueAbbreviations[list:{__String}]:=
With[
{maxLength=Max[StringLength/@list]},
SelectFirst[Transpose[Abbreviations[maxLength]/@list],DuplicateFreeQ,"no unique abbreviations possible"]
];
RequiredAbbreviationLength[""]="";
RequiredAbbreviationLength[input_String]:=Max[StringLength/@ShortestUniqueAbbreviations[StringSplit[input]]];
| #include <stdio.h>
#include <stdlib.h>
#include <string.h>
void process(int lineNum, char buffer[]) {
char days[7][64];
int i = 0, d = 0, j = 0;
while (buffer[i] != 0) {
if (buffer[i] == ' ') {
days[d][j] = '\0';
++d;
j = 0;
} else if (buffer[i] == '\n' || buffer[i] == '\r') {
days[d][j] = '\0';
++d;
break;
} else {
days[d][j] = buffer[i];
++j;
}
if (d >= 7) {
printf("There aren't 7 days in line %d\n", lineNum);
return;
}
++i;
}
if (buffer[i] == '\0') {
days[d][j] = '\0';
++d;
}
if (d < 7) {
printf("There aren't 7 days in line %d\n", lineNum);
return;
} else {
int len = 0;
for (len = 1; len < 64; ++len) {
int d1;
for (d1 = 0; d1 < 7; ++d1) {
int d2;
for (d2 = d1 + 1; d2 < 7; ++d2) {
int unique = 0;
for (i = 0; i < len; ++i) {
if (days[d1][i] != days[d2][i]) {
unique = 1;
break;
}
}
if (!unique) {
goto next_length;
}
}
}
printf("%2d ", len);
for (i = 0; i < 7; ++i) {
printf(" %s", days[i]);
}
printf("\n");
return;
next_length: {}
}
}
printf("Failed to find uniqueness within the bounds.");
}
int main() {
char buffer[1024];
int lineNum = 1, len;
FILE *fp;
fp = fopen("days_of_week.txt", "r");
while (1) {
memset(buffer, 0, sizeof(buffer));
fgets(buffer, sizeof(buffer), fp);
len = strlen(buffer);
if (len == 0 || buffer[len - 1] == '\0') {
break;
}
process(lineNum++, buffer);
}
fclose(fp);
return 0;
}
|
Translate the given Mathematica code snippet into C without altering its behavior. |
Abbreviations[maxLength_Integer][str_String]:=Array[StringTake[StringPadRight[str,maxLength,"_"],#]&,maxLength];
ShortestUniqueAbbreviations[list:{__String}]:=
With[
{maxLength=Max[StringLength/@list]},
SelectFirst[Transpose[Abbreviations[maxLength]/@list],DuplicateFreeQ,"no unique abbreviations possible"]
];
RequiredAbbreviationLength[""]="";
RequiredAbbreviationLength[input_String]:=Max[StringLength/@ShortestUniqueAbbreviations[StringSplit[input]]];
| #include <stdio.h>
#include <stdlib.h>
#include <string.h>
void process(int lineNum, char buffer[]) {
char days[7][64];
int i = 0, d = 0, j = 0;
while (buffer[i] != 0) {
if (buffer[i] == ' ') {
days[d][j] = '\0';
++d;
j = 0;
} else if (buffer[i] == '\n' || buffer[i] == '\r') {
days[d][j] = '\0';
++d;
break;
} else {
days[d][j] = buffer[i];
++j;
}
if (d >= 7) {
printf("There aren't 7 days in line %d\n", lineNum);
return;
}
++i;
}
if (buffer[i] == '\0') {
days[d][j] = '\0';
++d;
}
if (d < 7) {
printf("There aren't 7 days in line %d\n", lineNum);
return;
} else {
int len = 0;
for (len = 1; len < 64; ++len) {
int d1;
for (d1 = 0; d1 < 7; ++d1) {
int d2;
for (d2 = d1 + 1; d2 < 7; ++d2) {
int unique = 0;
for (i = 0; i < len; ++i) {
if (days[d1][i] != days[d2][i]) {
unique = 1;
break;
}
}
if (!unique) {
goto next_length;
}
}
}
printf("%2d ", len);
for (i = 0; i < 7; ++i) {
printf(" %s", days[i]);
}
printf("\n");
return;
next_length: {}
}
}
printf("Failed to find uniqueness within the bounds.");
}
int main() {
char buffer[1024];
int lineNum = 1, len;
FILE *fp;
fp = fopen("days_of_week.txt", "r");
while (1) {
memset(buffer, 0, sizeof(buffer));
fgets(buffer, sizeof(buffer), fp);
len = strlen(buffer);
if (len == 0 || buffer[len - 1] == '\0') {
break;
}
process(lineNum++, buffer);
}
fclose(fp);
return 0;
}
|
Ensure the translated C# code behaves exactly like the original Mathematica snippet. |
Abbreviations[maxLength_Integer][str_String]:=Array[StringTake[StringPadRight[str,maxLength,"_"],#]&,maxLength];
ShortestUniqueAbbreviations[list:{__String}]:=
With[
{maxLength=Max[StringLength/@list]},
SelectFirst[Transpose[Abbreviations[maxLength]/@list],DuplicateFreeQ,"no unique abbreviations possible"]
];
RequiredAbbreviationLength[""]="";
RequiredAbbreviationLength[input_String]:=Max[StringLength/@ShortestUniqueAbbreviations[StringSplit[input]]];
| using System;
using System.Collections.Generic;
namespace Abbreviations {
class Program {
static void Main(string[] args) {
string[] lines = System.IO.File.ReadAllLines("days_of_week.txt");
int i = 0;
foreach (string line in lines) {
i++;
if (line.Length > 0) {
var days = line.Split();
if (days.Length != 7) {
throw new Exception("There aren't 7 days in line " + i);
}
Dictionary<string, int> temp = new Dictionary<string, int>();
foreach (string day in days) {
if (temp.ContainsKey(day)) {
Console.WriteLine(" β {0}", line);
continue;
}
temp.Add(day, 1);
}
int len = 1;
while (true) {
temp.Clear();
foreach(string day in days) {
string key;
if (len < day.Length) {
key = day.Substring(0, len);
} else {
key = day;
}
if (temp.ContainsKey(key)) {
break;
}
temp.Add(key, 1);
}
if (temp.Count == 7) {
Console.WriteLine("{0,2:D} {1}", len, line);
break;
}
len++;
}
}
}
}
}
}
|
Change the following Mathematica code into C# without altering its purpose. |
Abbreviations[maxLength_Integer][str_String]:=Array[StringTake[StringPadRight[str,maxLength,"_"],#]&,maxLength];
ShortestUniqueAbbreviations[list:{__String}]:=
With[
{maxLength=Max[StringLength/@list]},
SelectFirst[Transpose[Abbreviations[maxLength]/@list],DuplicateFreeQ,"no unique abbreviations possible"]
];
RequiredAbbreviationLength[""]="";
RequiredAbbreviationLength[input_String]:=Max[StringLength/@ShortestUniqueAbbreviations[StringSplit[input]]];
| using System;
using System.Collections.Generic;
namespace Abbreviations {
class Program {
static void Main(string[] args) {
string[] lines = System.IO.File.ReadAllLines("days_of_week.txt");
int i = 0;
foreach (string line in lines) {
i++;
if (line.Length > 0) {
var days = line.Split();
if (days.Length != 7) {
throw new Exception("There aren't 7 days in line " + i);
}
Dictionary<string, int> temp = new Dictionary<string, int>();
foreach (string day in days) {
if (temp.ContainsKey(day)) {
Console.WriteLine(" β {0}", line);
continue;
}
temp.Add(day, 1);
}
int len = 1;
while (true) {
temp.Clear();
foreach(string day in days) {
string key;
if (len < day.Length) {
key = day.Substring(0, len);
} else {
key = day;
}
if (temp.ContainsKey(key)) {
break;
}
temp.Add(key, 1);
}
if (temp.Count == 7) {
Console.WriteLine("{0,2:D} {1}", len, line);
break;
}
len++;
}
}
}
}
}
}
|
Change the following Mathematica code into C++ without altering its purpose. |
Abbreviations[maxLength_Integer][str_String]:=Array[StringTake[StringPadRight[str,maxLength,"_"],#]&,maxLength];
ShortestUniqueAbbreviations[list:{__String}]:=
With[
{maxLength=Max[StringLength/@list]},
SelectFirst[Transpose[Abbreviations[maxLength]/@list],DuplicateFreeQ,"no unique abbreviations possible"]
];
RequiredAbbreviationLength[""]="";
RequiredAbbreviationLength[input_String]:=Max[StringLength/@ShortestUniqueAbbreviations[StringSplit[input]]];
| #include <iomanip>
#include <iostream>
#include <fstream>
#include <map>
#include <sstream>
#include <string>
#include <vector>
std::vector<std::string> split(const std::string& str, char delimiter) {
std::vector<std::string> tokens;
std::string token;
std::istringstream tokenStream(str);
while (std::getline(tokenStream, token, delimiter)) {
tokens.push_back(token);
}
return tokens;
}
int main() {
using namespace std;
string line;
int i = 0;
ifstream in("days_of_week.txt");
if (in.is_open()) {
while (getline(in, line)) {
i++;
if (line.empty()) {
continue;
}
auto days = split(line, ' ');
if (days.size() != 7) {
throw std::runtime_error("There aren't 7 days in line " + i);
}
map<string, int> temp;
for (auto& day : days) {
if (temp.find(day) != temp.end()) {
cerr << " β " << line << '\n';
continue;
}
temp[day] = 1;
}
int len = 1;
while (true) {
temp.clear();
for (auto& day : days) {
string key = day.substr(0, len);
if (temp.find(key) != temp.end()) {
break;
}
temp[key] = 1;
}
if (temp.size() == 7) {
cout << setw(2) << len << " " << line << '\n';
break;
}
len++;
}
}
}
return 0;
}
|
Convert this Mathematica block to C++, preserving its control flow and logic. |
Abbreviations[maxLength_Integer][str_String]:=Array[StringTake[StringPadRight[str,maxLength,"_"],#]&,maxLength];
ShortestUniqueAbbreviations[list:{__String}]:=
With[
{maxLength=Max[StringLength/@list]},
SelectFirst[Transpose[Abbreviations[maxLength]/@list],DuplicateFreeQ,"no unique abbreviations possible"]
];
RequiredAbbreviationLength[""]="";
RequiredAbbreviationLength[input_String]:=Max[StringLength/@ShortestUniqueAbbreviations[StringSplit[input]]];
| #include <iomanip>
#include <iostream>
#include <fstream>
#include <map>
#include <sstream>
#include <string>
#include <vector>
std::vector<std::string> split(const std::string& str, char delimiter) {
std::vector<std::string> tokens;
std::string token;
std::istringstream tokenStream(str);
while (std::getline(tokenStream, token, delimiter)) {
tokens.push_back(token);
}
return tokens;
}
int main() {
using namespace std;
string line;
int i = 0;
ifstream in("days_of_week.txt");
if (in.is_open()) {
while (getline(in, line)) {
i++;
if (line.empty()) {
continue;
}
auto days = split(line, ' ');
if (days.size() != 7) {
throw std::runtime_error("There aren't 7 days in line " + i);
}
map<string, int> temp;
for (auto& day : days) {
if (temp.find(day) != temp.end()) {
cerr << " β " << line << '\n';
continue;
}
temp[day] = 1;
}
int len = 1;
while (true) {
temp.clear();
for (auto& day : days) {
string key = day.substr(0, len);
if (temp.find(key) != temp.end()) {
break;
}
temp[key] = 1;
}
if (temp.size() == 7) {
cout << setw(2) << len << " " << line << '\n';
break;
}
len++;
}
}
}
return 0;
}
|
Produce a language-to-language conversion: from Mathematica to Java, same semantics. |
Abbreviations[maxLength_Integer][str_String]:=Array[StringTake[StringPadRight[str,maxLength,"_"],#]&,maxLength];
ShortestUniqueAbbreviations[list:{__String}]:=
With[
{maxLength=Max[StringLength/@list]},
SelectFirst[Transpose[Abbreviations[maxLength]/@list],DuplicateFreeQ,"no unique abbreviations possible"]
];
RequiredAbbreviationLength[""]="";
RequiredAbbreviationLength[input_String]:=Max[StringLength/@ShortestUniqueAbbreviations[StringSplit[input]]];
| import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class Abbreviations {
public static void main(String[] args) throws IOException {
Path path = Paths.get("days_of_week.txt");
List<String> readAllLines = Files.readAllLines(path);
for (int i = 0; i < readAllLines.size(); i++) {
String line = readAllLines.get(i);
if (line.length() == 0) continue;
String[] days = line.split(" ");
if (days.length != 7) throw new RuntimeException("There aren't 7 days on line " + (i + 1));
Map<String, Integer> temp = new HashMap<>();
for (String day : days) {
Integer count = temp.getOrDefault(day, 0);
temp.put(day, count + 1);
}
if (temp.size() < 7) {
System.out.print(" β ");
System.out.println(line);
continue;
}
int len = 1;
while (true) {
temp.clear();
for (String day : days) {
String sd;
if (len >= day.length()) {
sd = day;
} else {
sd = day.substring(0, len);
}
Integer count = temp.getOrDefault(sd, 0);
temp.put(sd, count + 1);
}
if (temp.size() == 7) {
System.out.printf("%2d %s\n", len, line);
break;
}
len++;
}
}
}
}
|
Transform the following Mathematica implementation into Java, maintaining the same output and logic. |
Abbreviations[maxLength_Integer][str_String]:=Array[StringTake[StringPadRight[str,maxLength,"_"],#]&,maxLength];
ShortestUniqueAbbreviations[list:{__String}]:=
With[
{maxLength=Max[StringLength/@list]},
SelectFirst[Transpose[Abbreviations[maxLength]/@list],DuplicateFreeQ,"no unique abbreviations possible"]
];
RequiredAbbreviationLength[""]="";
RequiredAbbreviationLength[input_String]:=Max[StringLength/@ShortestUniqueAbbreviations[StringSplit[input]]];
| import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class Abbreviations {
public static void main(String[] args) throws IOException {
Path path = Paths.get("days_of_week.txt");
List<String> readAllLines = Files.readAllLines(path);
for (int i = 0; i < readAllLines.size(); i++) {
String line = readAllLines.get(i);
if (line.length() == 0) continue;
String[] days = line.split(" ");
if (days.length != 7) throw new RuntimeException("There aren't 7 days on line " + (i + 1));
Map<String, Integer> temp = new HashMap<>();
for (String day : days) {
Integer count = temp.getOrDefault(day, 0);
temp.put(day, count + 1);
}
if (temp.size() < 7) {
System.out.print(" β ");
System.out.println(line);
continue;
}
int len = 1;
while (true) {
temp.clear();
for (String day : days) {
String sd;
if (len >= day.length()) {
sd = day;
} else {
sd = day.substring(0, len);
}
Integer count = temp.getOrDefault(sd, 0);
temp.put(sd, count + 1);
}
if (temp.size() == 7) {
System.out.printf("%2d %s\n", len, line);
break;
}
len++;
}
}
}
}
|
Convert this Mathematica snippet to Python and keep its semantics consistent. |
Abbreviations[maxLength_Integer][str_String]:=Array[StringTake[StringPadRight[str,maxLength,"_"],#]&,maxLength];
ShortestUniqueAbbreviations[list:{__String}]:=
With[
{maxLength=Max[StringLength/@list]},
SelectFirst[Transpose[Abbreviations[maxLength]/@list],DuplicateFreeQ,"no unique abbreviations possible"]
];
RequiredAbbreviationLength[""]="";
RequiredAbbreviationLength[input_String]:=Max[StringLength/@ShortestUniqueAbbreviations[StringSplit[input]]];
| def shortest_abbreviation_length(line, list_size):
words = line.split()
word_count = len(words)
if word_count != list_size:
raise ValueError(f'Not enough entries, expected {list_size} found {word_count}')
abbreviation_length = 1
abbreviations = set()
while(True):
abbreviations = {word[:abbreviation_length] for word in words}
if len(abbreviations) == list_size:
return abbreviation_length
abbreviation_length += 1
abbreviations.clear()
def automatic_abbreviations(filename, words_per_line):
with open(filename) as file:
for line in file:
line = line.rstrip()
if len(line) > 0:
length = shortest_abbreviation_length(line, words_per_line)
print(f'{length:2} {line}')
else:
print()
automatic_abbreviations('daysOfWeek.txt', 7)
|
Write the same code in Python as shown below in Mathematica. |
Abbreviations[maxLength_Integer][str_String]:=Array[StringTake[StringPadRight[str,maxLength,"_"],#]&,maxLength];
ShortestUniqueAbbreviations[list:{__String}]:=
With[
{maxLength=Max[StringLength/@list]},
SelectFirst[Transpose[Abbreviations[maxLength]/@list],DuplicateFreeQ,"no unique abbreviations possible"]
];
RequiredAbbreviationLength[""]="";
RequiredAbbreviationLength[input_String]:=Max[StringLength/@ShortestUniqueAbbreviations[StringSplit[input]]];
| def shortest_abbreviation_length(line, list_size):
words = line.split()
word_count = len(words)
if word_count != list_size:
raise ValueError(f'Not enough entries, expected {list_size} found {word_count}')
abbreviation_length = 1
abbreviations = set()
while(True):
abbreviations = {word[:abbreviation_length] for word in words}
if len(abbreviations) == list_size:
return abbreviation_length
abbreviation_length += 1
abbreviations.clear()
def automatic_abbreviations(filename, words_per_line):
with open(filename) as file:
for line in file:
line = line.rstrip()
if len(line) > 0:
length = shortest_abbreviation_length(line, words_per_line)
print(f'{length:2} {line}')
else:
print()
automatic_abbreviations('daysOfWeek.txt', 7)
|
Please provide an equivalent version of this Mathematica code in VB. |
Abbreviations[maxLength_Integer][str_String]:=Array[StringTake[StringPadRight[str,maxLength,"_"],#]&,maxLength];
ShortestUniqueAbbreviations[list:{__String}]:=
With[
{maxLength=Max[StringLength/@list]},
SelectFirst[Transpose[Abbreviations[maxLength]/@list],DuplicateFreeQ,"no unique abbreviations possible"]
];
RequiredAbbreviationLength[""]="";
RequiredAbbreviationLength[input_String]:=Max[StringLength/@ShortestUniqueAbbreviations[StringSplit[input]]];
| Function MinimalLenght(strLine As String) As Integer
Dim myVar As Variant, I As Integer, Flag As Boolean, myColl As Collection, Count As Integer
myVar = Split(strLine, " ")
Count = 0
Do
Set myColl = New Collection
Count = Count + 1
On Error Resume Next
Do
myColl.Add Left$(myVar(I), Count), Left$(myVar(I), Count)
I = I + 1
Loop While Err.Number = 0 And I <= UBound(myVar)
Flag = Err.Number = 0
On Error GoTo 0
I = 0
Set myColl = Nothing
Loop While Not Flag
MinimalLenght = Count
End Function
|
Keep all operations the same but rewrite the snippet in VB. |
Abbreviations[maxLength_Integer][str_String]:=Array[StringTake[StringPadRight[str,maxLength,"_"],#]&,maxLength];
ShortestUniqueAbbreviations[list:{__String}]:=
With[
{maxLength=Max[StringLength/@list]},
SelectFirst[Transpose[Abbreviations[maxLength]/@list],DuplicateFreeQ,"no unique abbreviations possible"]
];
RequiredAbbreviationLength[""]="";
RequiredAbbreviationLength[input_String]:=Max[StringLength/@ShortestUniqueAbbreviations[StringSplit[input]]];
| Function MinimalLenght(strLine As String) As Integer
Dim myVar As Variant, I As Integer, Flag As Boolean, myColl As Collection, Count As Integer
myVar = Split(strLine, " ")
Count = 0
Do
Set myColl = New Collection
Count = Count + 1
On Error Resume Next
Do
myColl.Add Left$(myVar(I), Count), Left$(myVar(I), Count)
I = I + 1
Loop While Err.Number = 0 And I <= UBound(myVar)
Flag = Err.Number = 0
On Error GoTo 0
I = 0
Set myColl = Nothing
Loop While Not Flag
MinimalLenght = Count
End Function
|
Preserve the algorithm and functionality while converting the code from Mathematica to Go. |
Abbreviations[maxLength_Integer][str_String]:=Array[StringTake[StringPadRight[str,maxLength,"_"],#]&,maxLength];
ShortestUniqueAbbreviations[list:{__String}]:=
With[
{maxLength=Max[StringLength/@list]},
SelectFirst[Transpose[Abbreviations[maxLength]/@list],DuplicateFreeQ,"no unique abbreviations possible"]
];
RequiredAbbreviationLength[""]="";
RequiredAbbreviationLength[input_String]:=Max[StringLength/@ShortestUniqueAbbreviations[StringSplit[input]]];
| package main
import(
"bufio"
"fmt"
"os"
"strings"
)
func distinctStrings(strs []string) []string {
len := len(strs)
set := make(map[string]bool, len)
distinct := make([]string, 0, len)
for _, str := range strs {
if !set[str] {
distinct = append(distinct, str)
set[str] = true
}
}
return distinct
}
func takeRunes(s string, n int) string {
i := 0
for j := range s {
if i == n {
return s[:j]
}
i++
}
return s
}
func main() {
file, err := os.Open("days_of_week.txt")
if err != nil {
fmt.Println("Unable to open file.")
return
}
defer file.Close()
reader := bufio.NewReader(file)
lineCount := 0
for {
line, err := reader.ReadString('\n')
if err != nil {
return
}
line = strings.TrimSpace(line)
lineCount++
if line == "" {
fmt.Println()
continue
}
days := strings.Fields(line)
daysLen := len(days)
if (len(days) != 7) {
fmt.Println("There aren't 7 days in line", lineCount)
return
}
if len(distinctStrings(days)) != 7 {
fmt.Println(" β ", line)
continue
}
for abbrevLen := 1; ; abbrevLen++ {
abbrevs := make([]string, daysLen)
for i := 0; i < daysLen; i++ {
abbrevs[i] = takeRunes(days[i], abbrevLen)
}
if len(distinctStrings(abbrevs)) == 7 {
fmt.Printf("%2d %s\n", abbrevLen, line)
break
}
}
}
}
|
Port the following code from Mathematica to Go with equivalent syntax and logic. |
Abbreviations[maxLength_Integer][str_String]:=Array[StringTake[StringPadRight[str,maxLength,"_"],#]&,maxLength];
ShortestUniqueAbbreviations[list:{__String}]:=
With[
{maxLength=Max[StringLength/@list]},
SelectFirst[Transpose[Abbreviations[maxLength]/@list],DuplicateFreeQ,"no unique abbreviations possible"]
];
RequiredAbbreviationLength[""]="";
RequiredAbbreviationLength[input_String]:=Max[StringLength/@ShortestUniqueAbbreviations[StringSplit[input]]];
| package main
import(
"bufio"
"fmt"
"os"
"strings"
)
func distinctStrings(strs []string) []string {
len := len(strs)
set := make(map[string]bool, len)
distinct := make([]string, 0, len)
for _, str := range strs {
if !set[str] {
distinct = append(distinct, str)
set[str] = true
}
}
return distinct
}
func takeRunes(s string, n int) string {
i := 0
for j := range s {
if i == n {
return s[:j]
}
i++
}
return s
}
func main() {
file, err := os.Open("days_of_week.txt")
if err != nil {
fmt.Println("Unable to open file.")
return
}
defer file.Close()
reader := bufio.NewReader(file)
lineCount := 0
for {
line, err := reader.ReadString('\n')
if err != nil {
return
}
line = strings.TrimSpace(line)
lineCount++
if line == "" {
fmt.Println()
continue
}
days := strings.Fields(line)
daysLen := len(days)
if (len(days) != 7) {
fmt.Println("There aren't 7 days in line", lineCount)
return
}
if len(distinctStrings(days)) != 7 {
fmt.Println(" β ", line)
continue
}
for abbrevLen := 1; ; abbrevLen++ {
abbrevs := make([]string, daysLen)
for i := 0; i < daysLen; i++ {
abbrevs[i] = takeRunes(days[i], abbrevLen)
}
if len(distinctStrings(abbrevs)) == 7 {
fmt.Printf("%2d %s\n", abbrevLen, line)
break
}
}
}
}
|
Translate this program into C but keep the logic exactly as in Nim. | import sets
import unicode
type Runes = seq[Rune]
var linenum = 0
for line in lines("days.txt"):
inc linenum
if line.len > 0:
var days: seq[Runes]
for day in line.splitWhitespace():
days.add(day.toLower.toRunes)
if days.len != 7:
echo "Wrong number of days at line ", linenum
var index = 0
while true:
var abbrevs: HashSet[seq[Rune]]
for day in days:
abbrevs.incl(day[0..min(index, day.high)])
if abbrevs.card == 7:
break
inc index
echo index + 1, " ", line
else:
echo line
| #include <stdio.h>
#include <stdlib.h>
#include <string.h>
void process(int lineNum, char buffer[]) {
char days[7][64];
int i = 0, d = 0, j = 0;
while (buffer[i] != 0) {
if (buffer[i] == ' ') {
days[d][j] = '\0';
++d;
j = 0;
} else if (buffer[i] == '\n' || buffer[i] == '\r') {
days[d][j] = '\0';
++d;
break;
} else {
days[d][j] = buffer[i];
++j;
}
if (d >= 7) {
printf("There aren't 7 days in line %d\n", lineNum);
return;
}
++i;
}
if (buffer[i] == '\0') {
days[d][j] = '\0';
++d;
}
if (d < 7) {
printf("There aren't 7 days in line %d\n", lineNum);
return;
} else {
int len = 0;
for (len = 1; len < 64; ++len) {
int d1;
for (d1 = 0; d1 < 7; ++d1) {
int d2;
for (d2 = d1 + 1; d2 < 7; ++d2) {
int unique = 0;
for (i = 0; i < len; ++i) {
if (days[d1][i] != days[d2][i]) {
unique = 1;
break;
}
}
if (!unique) {
goto next_length;
}
}
}
printf("%2d ", len);
for (i = 0; i < 7; ++i) {
printf(" %s", days[i]);
}
printf("\n");
return;
next_length: {}
}
}
printf("Failed to find uniqueness within the bounds.");
}
int main() {
char buffer[1024];
int lineNum = 1, len;
FILE *fp;
fp = fopen("days_of_week.txt", "r");
while (1) {
memset(buffer, 0, sizeof(buffer));
fgets(buffer, sizeof(buffer), fp);
len = strlen(buffer);
if (len == 0 || buffer[len - 1] == '\0') {
break;
}
process(lineNum++, buffer);
}
fclose(fp);
return 0;
}
|
Rewrite the snippet below in C so it works the same as the original Nim code. | import sets
import unicode
type Runes = seq[Rune]
var linenum = 0
for line in lines("days.txt"):
inc linenum
if line.len > 0:
var days: seq[Runes]
for day in line.splitWhitespace():
days.add(day.toLower.toRunes)
if days.len != 7:
echo "Wrong number of days at line ", linenum
var index = 0
while true:
var abbrevs: HashSet[seq[Rune]]
for day in days:
abbrevs.incl(day[0..min(index, day.high)])
if abbrevs.card == 7:
break
inc index
echo index + 1, " ", line
else:
echo line
| #include <stdio.h>
#include <stdlib.h>
#include <string.h>
void process(int lineNum, char buffer[]) {
char days[7][64];
int i = 0, d = 0, j = 0;
while (buffer[i] != 0) {
if (buffer[i] == ' ') {
days[d][j] = '\0';
++d;
j = 0;
} else if (buffer[i] == '\n' || buffer[i] == '\r') {
days[d][j] = '\0';
++d;
break;
} else {
days[d][j] = buffer[i];
++j;
}
if (d >= 7) {
printf("There aren't 7 days in line %d\n", lineNum);
return;
}
++i;
}
if (buffer[i] == '\0') {
days[d][j] = '\0';
++d;
}
if (d < 7) {
printf("There aren't 7 days in line %d\n", lineNum);
return;
} else {
int len = 0;
for (len = 1; len < 64; ++len) {
int d1;
for (d1 = 0; d1 < 7; ++d1) {
int d2;
for (d2 = d1 + 1; d2 < 7; ++d2) {
int unique = 0;
for (i = 0; i < len; ++i) {
if (days[d1][i] != days[d2][i]) {
unique = 1;
break;
}
}
if (!unique) {
goto next_length;
}
}
}
printf("%2d ", len);
for (i = 0; i < 7; ++i) {
printf(" %s", days[i]);
}
printf("\n");
return;
next_length: {}
}
}
printf("Failed to find uniqueness within the bounds.");
}
int main() {
char buffer[1024];
int lineNum = 1, len;
FILE *fp;
fp = fopen("days_of_week.txt", "r");
while (1) {
memset(buffer, 0, sizeof(buffer));
fgets(buffer, sizeof(buffer), fp);
len = strlen(buffer);
if (len == 0 || buffer[len - 1] == '\0') {
break;
}
process(lineNum++, buffer);
}
fclose(fp);
return 0;
}
|
Transform the following Nim implementation into C#, maintaining the same output and logic. | import sets
import unicode
type Runes = seq[Rune]
var linenum = 0
for line in lines("days.txt"):
inc linenum
if line.len > 0:
var days: seq[Runes]
for day in line.splitWhitespace():
days.add(day.toLower.toRunes)
if days.len != 7:
echo "Wrong number of days at line ", linenum
var index = 0
while true:
var abbrevs: HashSet[seq[Rune]]
for day in days:
abbrevs.incl(day[0..min(index, day.high)])
if abbrevs.card == 7:
break
inc index
echo index + 1, " ", line
else:
echo line
| using System;
using System.Collections.Generic;
namespace Abbreviations {
class Program {
static void Main(string[] args) {
string[] lines = System.IO.File.ReadAllLines("days_of_week.txt");
int i = 0;
foreach (string line in lines) {
i++;
if (line.Length > 0) {
var days = line.Split();
if (days.Length != 7) {
throw new Exception("There aren't 7 days in line " + i);
}
Dictionary<string, int> temp = new Dictionary<string, int>();
foreach (string day in days) {
if (temp.ContainsKey(day)) {
Console.WriteLine(" β {0}", line);
continue;
}
temp.Add(day, 1);
}
int len = 1;
while (true) {
temp.Clear();
foreach(string day in days) {
string key;
if (len < day.Length) {
key = day.Substring(0, len);
} else {
key = day;
}
if (temp.ContainsKey(key)) {
break;
}
temp.Add(key, 1);
}
if (temp.Count == 7) {
Console.WriteLine("{0,2:D} {1}", len, line);
break;
}
len++;
}
}
}
}
}
}
|
Transform the following Nim implementation into C#, maintaining the same output and logic. | import sets
import unicode
type Runes = seq[Rune]
var linenum = 0
for line in lines("days.txt"):
inc linenum
if line.len > 0:
var days: seq[Runes]
for day in line.splitWhitespace():
days.add(day.toLower.toRunes)
if days.len != 7:
echo "Wrong number of days at line ", linenum
var index = 0
while true:
var abbrevs: HashSet[seq[Rune]]
for day in days:
abbrevs.incl(day[0..min(index, day.high)])
if abbrevs.card == 7:
break
inc index
echo index + 1, " ", line
else:
echo line
| using System;
using System.Collections.Generic;
namespace Abbreviations {
class Program {
static void Main(string[] args) {
string[] lines = System.IO.File.ReadAllLines("days_of_week.txt");
int i = 0;
foreach (string line in lines) {
i++;
if (line.Length > 0) {
var days = line.Split();
if (days.Length != 7) {
throw new Exception("There aren't 7 days in line " + i);
}
Dictionary<string, int> temp = new Dictionary<string, int>();
foreach (string day in days) {
if (temp.ContainsKey(day)) {
Console.WriteLine(" β {0}", line);
continue;
}
temp.Add(day, 1);
}
int len = 1;
while (true) {
temp.Clear();
foreach(string day in days) {
string key;
if (len < day.Length) {
key = day.Substring(0, len);
} else {
key = day;
}
if (temp.ContainsKey(key)) {
break;
}
temp.Add(key, 1);
}
if (temp.Count == 7) {
Console.WriteLine("{0,2:D} {1}", len, line);
break;
}
len++;
}
}
}
}
}
}
|
Port the following code from Nim to C++ with equivalent syntax and logic. | import sets
import unicode
type Runes = seq[Rune]
var linenum = 0
for line in lines("days.txt"):
inc linenum
if line.len > 0:
var days: seq[Runes]
for day in line.splitWhitespace():
days.add(day.toLower.toRunes)
if days.len != 7:
echo "Wrong number of days at line ", linenum
var index = 0
while true:
var abbrevs: HashSet[seq[Rune]]
for day in days:
abbrevs.incl(day[0..min(index, day.high)])
if abbrevs.card == 7:
break
inc index
echo index + 1, " ", line
else:
echo line
| #include <iomanip>
#include <iostream>
#include <fstream>
#include <map>
#include <sstream>
#include <string>
#include <vector>
std::vector<std::string> split(const std::string& str, char delimiter) {
std::vector<std::string> tokens;
std::string token;
std::istringstream tokenStream(str);
while (std::getline(tokenStream, token, delimiter)) {
tokens.push_back(token);
}
return tokens;
}
int main() {
using namespace std;
string line;
int i = 0;
ifstream in("days_of_week.txt");
if (in.is_open()) {
while (getline(in, line)) {
i++;
if (line.empty()) {
continue;
}
auto days = split(line, ' ');
if (days.size() != 7) {
throw std::runtime_error("There aren't 7 days in line " + i);
}
map<string, int> temp;
for (auto& day : days) {
if (temp.find(day) != temp.end()) {
cerr << " β " << line << '\n';
continue;
}
temp[day] = 1;
}
int len = 1;
while (true) {
temp.clear();
for (auto& day : days) {
string key = day.substr(0, len);
if (temp.find(key) != temp.end()) {
break;
}
temp[key] = 1;
}
if (temp.size() == 7) {
cout << setw(2) << len << " " << line << '\n';
break;
}
len++;
}
}
}
return 0;
}
|
Ensure the translated C++ code behaves exactly like the original Nim snippet. | import sets
import unicode
type Runes = seq[Rune]
var linenum = 0
for line in lines("days.txt"):
inc linenum
if line.len > 0:
var days: seq[Runes]
for day in line.splitWhitespace():
days.add(day.toLower.toRunes)
if days.len != 7:
echo "Wrong number of days at line ", linenum
var index = 0
while true:
var abbrevs: HashSet[seq[Rune]]
for day in days:
abbrevs.incl(day[0..min(index, day.high)])
if abbrevs.card == 7:
break
inc index
echo index + 1, " ", line
else:
echo line
| #include <iomanip>
#include <iostream>
#include <fstream>
#include <map>
#include <sstream>
#include <string>
#include <vector>
std::vector<std::string> split(const std::string& str, char delimiter) {
std::vector<std::string> tokens;
std::string token;
std::istringstream tokenStream(str);
while (std::getline(tokenStream, token, delimiter)) {
tokens.push_back(token);
}
return tokens;
}
int main() {
using namespace std;
string line;
int i = 0;
ifstream in("days_of_week.txt");
if (in.is_open()) {
while (getline(in, line)) {
i++;
if (line.empty()) {
continue;
}
auto days = split(line, ' ');
if (days.size() != 7) {
throw std::runtime_error("There aren't 7 days in line " + i);
}
map<string, int> temp;
for (auto& day : days) {
if (temp.find(day) != temp.end()) {
cerr << " β " << line << '\n';
continue;
}
temp[day] = 1;
}
int len = 1;
while (true) {
temp.clear();
for (auto& day : days) {
string key = day.substr(0, len);
if (temp.find(key) != temp.end()) {
break;
}
temp[key] = 1;
}
if (temp.size() == 7) {
cout << setw(2) << len << " " << line << '\n';
break;
}
len++;
}
}
}
return 0;
}
|
Convert the following code from Nim to Java, ensuring the logic remains intact. | import sets
import unicode
type Runes = seq[Rune]
var linenum = 0
for line in lines("days.txt"):
inc linenum
if line.len > 0:
var days: seq[Runes]
for day in line.splitWhitespace():
days.add(day.toLower.toRunes)
if days.len != 7:
echo "Wrong number of days at line ", linenum
var index = 0
while true:
var abbrevs: HashSet[seq[Rune]]
for day in days:
abbrevs.incl(day[0..min(index, day.high)])
if abbrevs.card == 7:
break
inc index
echo index + 1, " ", line
else:
echo line
| import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class Abbreviations {
public static void main(String[] args) throws IOException {
Path path = Paths.get("days_of_week.txt");
List<String> readAllLines = Files.readAllLines(path);
for (int i = 0; i < readAllLines.size(); i++) {
String line = readAllLines.get(i);
if (line.length() == 0) continue;
String[] days = line.split(" ");
if (days.length != 7) throw new RuntimeException("There aren't 7 days on line " + (i + 1));
Map<String, Integer> temp = new HashMap<>();
for (String day : days) {
Integer count = temp.getOrDefault(day, 0);
temp.put(day, count + 1);
}
if (temp.size() < 7) {
System.out.print(" β ");
System.out.println(line);
continue;
}
int len = 1;
while (true) {
temp.clear();
for (String day : days) {
String sd;
if (len >= day.length()) {
sd = day;
} else {
sd = day.substring(0, len);
}
Integer count = temp.getOrDefault(sd, 0);
temp.put(sd, count + 1);
}
if (temp.size() == 7) {
System.out.printf("%2d %s\n", len, line);
break;
}
len++;
}
}
}
}
|
Convert the following code from Nim to Java, ensuring the logic remains intact. | import sets
import unicode
type Runes = seq[Rune]
var linenum = 0
for line in lines("days.txt"):
inc linenum
if line.len > 0:
var days: seq[Runes]
for day in line.splitWhitespace():
days.add(day.toLower.toRunes)
if days.len != 7:
echo "Wrong number of days at line ", linenum
var index = 0
while true:
var abbrevs: HashSet[seq[Rune]]
for day in days:
abbrevs.incl(day[0..min(index, day.high)])
if abbrevs.card == 7:
break
inc index
echo index + 1, " ", line
else:
echo line
| import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class Abbreviations {
public static void main(String[] args) throws IOException {
Path path = Paths.get("days_of_week.txt");
List<String> readAllLines = Files.readAllLines(path);
for (int i = 0; i < readAllLines.size(); i++) {
String line = readAllLines.get(i);
if (line.length() == 0) continue;
String[] days = line.split(" ");
if (days.length != 7) throw new RuntimeException("There aren't 7 days on line " + (i + 1));
Map<String, Integer> temp = new HashMap<>();
for (String day : days) {
Integer count = temp.getOrDefault(day, 0);
temp.put(day, count + 1);
}
if (temp.size() < 7) {
System.out.print(" β ");
System.out.println(line);
continue;
}
int len = 1;
while (true) {
temp.clear();
for (String day : days) {
String sd;
if (len >= day.length()) {
sd = day;
} else {
sd = day.substring(0, len);
}
Integer count = temp.getOrDefault(sd, 0);
temp.put(sd, count + 1);
}
if (temp.size() == 7) {
System.out.printf("%2d %s\n", len, line);
break;
}
len++;
}
}
}
}
|
Preserve the algorithm and functionality while converting the code from Nim to Python. | import sets
import unicode
type Runes = seq[Rune]
var linenum = 0
for line in lines("days.txt"):
inc linenum
if line.len > 0:
var days: seq[Runes]
for day in line.splitWhitespace():
days.add(day.toLower.toRunes)
if days.len != 7:
echo "Wrong number of days at line ", linenum
var index = 0
while true:
var abbrevs: HashSet[seq[Rune]]
for day in days:
abbrevs.incl(day[0..min(index, day.high)])
if abbrevs.card == 7:
break
inc index
echo index + 1, " ", line
else:
echo line
| def shortest_abbreviation_length(line, list_size):
words = line.split()
word_count = len(words)
if word_count != list_size:
raise ValueError(f'Not enough entries, expected {list_size} found {word_count}')
abbreviation_length = 1
abbreviations = set()
while(True):
abbreviations = {word[:abbreviation_length] for word in words}
if len(abbreviations) == list_size:
return abbreviation_length
abbreviation_length += 1
abbreviations.clear()
def automatic_abbreviations(filename, words_per_line):
with open(filename) as file:
for line in file:
line = line.rstrip()
if len(line) > 0:
length = shortest_abbreviation_length(line, words_per_line)
print(f'{length:2} {line}')
else:
print()
automatic_abbreviations('daysOfWeek.txt', 7)
|
Convert this Nim snippet to Python and keep its semantics consistent. | import sets
import unicode
type Runes = seq[Rune]
var linenum = 0
for line in lines("days.txt"):
inc linenum
if line.len > 0:
var days: seq[Runes]
for day in line.splitWhitespace():
days.add(day.toLower.toRunes)
if days.len != 7:
echo "Wrong number of days at line ", linenum
var index = 0
while true:
var abbrevs: HashSet[seq[Rune]]
for day in days:
abbrevs.incl(day[0..min(index, day.high)])
if abbrevs.card == 7:
break
inc index
echo index + 1, " ", line
else:
echo line
| def shortest_abbreviation_length(line, list_size):
words = line.split()
word_count = len(words)
if word_count != list_size:
raise ValueError(f'Not enough entries, expected {list_size} found {word_count}')
abbreviation_length = 1
abbreviations = set()
while(True):
abbreviations = {word[:abbreviation_length] for word in words}
if len(abbreviations) == list_size:
return abbreviation_length
abbreviation_length += 1
abbreviations.clear()
def automatic_abbreviations(filename, words_per_line):
with open(filename) as file:
for line in file:
line = line.rstrip()
if len(line) > 0:
length = shortest_abbreviation_length(line, words_per_line)
print(f'{length:2} {line}')
else:
print()
automatic_abbreviations('daysOfWeek.txt', 7)
|
Write the same algorithm in VB as shown in this Nim implementation. | import sets
import unicode
type Runes = seq[Rune]
var linenum = 0
for line in lines("days.txt"):
inc linenum
if line.len > 0:
var days: seq[Runes]
for day in line.splitWhitespace():
days.add(day.toLower.toRunes)
if days.len != 7:
echo "Wrong number of days at line ", linenum
var index = 0
while true:
var abbrevs: HashSet[seq[Rune]]
for day in days:
abbrevs.incl(day[0..min(index, day.high)])
if abbrevs.card == 7:
break
inc index
echo index + 1, " ", line
else:
echo line
| Function MinimalLenght(strLine As String) As Integer
Dim myVar As Variant, I As Integer, Flag As Boolean, myColl As Collection, Count As Integer
myVar = Split(strLine, " ")
Count = 0
Do
Set myColl = New Collection
Count = Count + 1
On Error Resume Next
Do
myColl.Add Left$(myVar(I), Count), Left$(myVar(I), Count)
I = I + 1
Loop While Err.Number = 0 And I <= UBound(myVar)
Flag = Err.Number = 0
On Error GoTo 0
I = 0
Set myColl = Nothing
Loop While Not Flag
MinimalLenght = Count
End Function
|
Please provide an equivalent version of this Nim code in VB. | import sets
import unicode
type Runes = seq[Rune]
var linenum = 0
for line in lines("days.txt"):
inc linenum
if line.len > 0:
var days: seq[Runes]
for day in line.splitWhitespace():
days.add(day.toLower.toRunes)
if days.len != 7:
echo "Wrong number of days at line ", linenum
var index = 0
while true:
var abbrevs: HashSet[seq[Rune]]
for day in days:
abbrevs.incl(day[0..min(index, day.high)])
if abbrevs.card == 7:
break
inc index
echo index + 1, " ", line
else:
echo line
| Function MinimalLenght(strLine As String) As Integer
Dim myVar As Variant, I As Integer, Flag As Boolean, myColl As Collection, Count As Integer
myVar = Split(strLine, " ")
Count = 0
Do
Set myColl = New Collection
Count = Count + 1
On Error Resume Next
Do
myColl.Add Left$(myVar(I), Count), Left$(myVar(I), Count)
I = I + 1
Loop While Err.Number = 0 And I <= UBound(myVar)
Flag = Err.Number = 0
On Error GoTo 0
I = 0
Set myColl = Nothing
Loop While Not Flag
MinimalLenght = Count
End Function
|
Write the same algorithm in Go as shown in this Nim implementation. | import sets
import unicode
type Runes = seq[Rune]
var linenum = 0
for line in lines("days.txt"):
inc linenum
if line.len > 0:
var days: seq[Runes]
for day in line.splitWhitespace():
days.add(day.toLower.toRunes)
if days.len != 7:
echo "Wrong number of days at line ", linenum
var index = 0
while true:
var abbrevs: HashSet[seq[Rune]]
for day in days:
abbrevs.incl(day[0..min(index, day.high)])
if abbrevs.card == 7:
break
inc index
echo index + 1, " ", line
else:
echo line
| package main
import(
"bufio"
"fmt"
"os"
"strings"
)
func distinctStrings(strs []string) []string {
len := len(strs)
set := make(map[string]bool, len)
distinct := make([]string, 0, len)
for _, str := range strs {
if !set[str] {
distinct = append(distinct, str)
set[str] = true
}
}
return distinct
}
func takeRunes(s string, n int) string {
i := 0
for j := range s {
if i == n {
return s[:j]
}
i++
}
return s
}
func main() {
file, err := os.Open("days_of_week.txt")
if err != nil {
fmt.Println("Unable to open file.")
return
}
defer file.Close()
reader := bufio.NewReader(file)
lineCount := 0
for {
line, err := reader.ReadString('\n')
if err != nil {
return
}
line = strings.TrimSpace(line)
lineCount++
if line == "" {
fmt.Println()
continue
}
days := strings.Fields(line)
daysLen := len(days)
if (len(days) != 7) {
fmt.Println("There aren't 7 days in line", lineCount)
return
}
if len(distinctStrings(days)) != 7 {
fmt.Println(" β ", line)
continue
}
for abbrevLen := 1; ; abbrevLen++ {
abbrevs := make([]string, daysLen)
for i := 0; i < daysLen; i++ {
abbrevs[i] = takeRunes(days[i], abbrevLen)
}
if len(distinctStrings(abbrevs)) == 7 {
fmt.Printf("%2d %s\n", abbrevLen, line)
break
}
}
}
}
|
Port the following code from Nim to Go with equivalent syntax and logic. | import sets
import unicode
type Runes = seq[Rune]
var linenum = 0
for line in lines("days.txt"):
inc linenum
if line.len > 0:
var days: seq[Runes]
for day in line.splitWhitespace():
days.add(day.toLower.toRunes)
if days.len != 7:
echo "Wrong number of days at line ", linenum
var index = 0
while true:
var abbrevs: HashSet[seq[Rune]]
for day in days:
abbrevs.incl(day[0..min(index, day.high)])
if abbrevs.card == 7:
break
inc index
echo index + 1, " ", line
else:
echo line
| package main
import(
"bufio"
"fmt"
"os"
"strings"
)
func distinctStrings(strs []string) []string {
len := len(strs)
set := make(map[string]bool, len)
distinct := make([]string, 0, len)
for _, str := range strs {
if !set[str] {
distinct = append(distinct, str)
set[str] = true
}
}
return distinct
}
func takeRunes(s string, n int) string {
i := 0
for j := range s {
if i == n {
return s[:j]
}
i++
}
return s
}
func main() {
file, err := os.Open("days_of_week.txt")
if err != nil {
fmt.Println("Unable to open file.")
return
}
defer file.Close()
reader := bufio.NewReader(file)
lineCount := 0
for {
line, err := reader.ReadString('\n')
if err != nil {
return
}
line = strings.TrimSpace(line)
lineCount++
if line == "" {
fmt.Println()
continue
}
days := strings.Fields(line)
daysLen := len(days)
if (len(days) != 7) {
fmt.Println("There aren't 7 days in line", lineCount)
return
}
if len(distinctStrings(days)) != 7 {
fmt.Println(" β ", line)
continue
}
for abbrevLen := 1; ; abbrevLen++ {
abbrevs := make([]string, daysLen)
for i := 0; i < daysLen; i++ {
abbrevs[i] = takeRunes(days[i], abbrevLen)
}
if len(distinctStrings(abbrevs)) == 7 {
fmt.Printf("%2d %s\n", abbrevLen, line)
break
}
}
}
}
|
Produce a language-to-language conversion: from Perl to C, same semantics. | use strict;
use utf8;
binmode STDOUT, ":utf8";
sub auto_abbreviate {
my($string) = @_;
my @words = split ' ', $string;
my $max = 0;
return '' unless @words;
map { $max = length($_) if length($_) > $max } @words;
for $i (1..$max) {
my %seen;
return $i if @words == grep {!$seen{substr($_,0,$i)}++} @words;
}
return 'β';
}
open $fh, '<:encoding(UTF-8)', 'DoWAKA.txt';
while ($_ = <$fh>) {
print "$.) " . auto_abbreviate($_) . ' ' . $_;
}
| #include <stdio.h>
#include <stdlib.h>
#include <string.h>
void process(int lineNum, char buffer[]) {
char days[7][64];
int i = 0, d = 0, j = 0;
while (buffer[i] != 0) {
if (buffer[i] == ' ') {
days[d][j] = '\0';
++d;
j = 0;
} else if (buffer[i] == '\n' || buffer[i] == '\r') {
days[d][j] = '\0';
++d;
break;
} else {
days[d][j] = buffer[i];
++j;
}
if (d >= 7) {
printf("There aren't 7 days in line %d\n", lineNum);
return;
}
++i;
}
if (buffer[i] == '\0') {
days[d][j] = '\0';
++d;
}
if (d < 7) {
printf("There aren't 7 days in line %d\n", lineNum);
return;
} else {
int len = 0;
for (len = 1; len < 64; ++len) {
int d1;
for (d1 = 0; d1 < 7; ++d1) {
int d2;
for (d2 = d1 + 1; d2 < 7; ++d2) {
int unique = 0;
for (i = 0; i < len; ++i) {
if (days[d1][i] != days[d2][i]) {
unique = 1;
break;
}
}
if (!unique) {
goto next_length;
}
}
}
printf("%2d ", len);
for (i = 0; i < 7; ++i) {
printf(" %s", days[i]);
}
printf("\n");
return;
next_length: {}
}
}
printf("Failed to find uniqueness within the bounds.");
}
int main() {
char buffer[1024];
int lineNum = 1, len;
FILE *fp;
fp = fopen("days_of_week.txt", "r");
while (1) {
memset(buffer, 0, sizeof(buffer));
fgets(buffer, sizeof(buffer), fp);
len = strlen(buffer);
if (len == 0 || buffer[len - 1] == '\0') {
break;
}
process(lineNum++, buffer);
}
fclose(fp);
return 0;
}
|
Convert this Perl block to C, preserving its control flow and logic. | use strict;
use utf8;
binmode STDOUT, ":utf8";
sub auto_abbreviate {
my($string) = @_;
my @words = split ' ', $string;
my $max = 0;
return '' unless @words;
map { $max = length($_) if length($_) > $max } @words;
for $i (1..$max) {
my %seen;
return $i if @words == grep {!$seen{substr($_,0,$i)}++} @words;
}
return 'β';
}
open $fh, '<:encoding(UTF-8)', 'DoWAKA.txt';
while ($_ = <$fh>) {
print "$.) " . auto_abbreviate($_) . ' ' . $_;
}
| #include <stdio.h>
#include <stdlib.h>
#include <string.h>
void process(int lineNum, char buffer[]) {
char days[7][64];
int i = 0, d = 0, j = 0;
while (buffer[i] != 0) {
if (buffer[i] == ' ') {
days[d][j] = '\0';
++d;
j = 0;
} else if (buffer[i] == '\n' || buffer[i] == '\r') {
days[d][j] = '\0';
++d;
break;
} else {
days[d][j] = buffer[i];
++j;
}
if (d >= 7) {
printf("There aren't 7 days in line %d\n", lineNum);
return;
}
++i;
}
if (buffer[i] == '\0') {
days[d][j] = '\0';
++d;
}
if (d < 7) {
printf("There aren't 7 days in line %d\n", lineNum);
return;
} else {
int len = 0;
for (len = 1; len < 64; ++len) {
int d1;
for (d1 = 0; d1 < 7; ++d1) {
int d2;
for (d2 = d1 + 1; d2 < 7; ++d2) {
int unique = 0;
for (i = 0; i < len; ++i) {
if (days[d1][i] != days[d2][i]) {
unique = 1;
break;
}
}
if (!unique) {
goto next_length;
}
}
}
printf("%2d ", len);
for (i = 0; i < 7; ++i) {
printf(" %s", days[i]);
}
printf("\n");
return;
next_length: {}
}
}
printf("Failed to find uniqueness within the bounds.");
}
int main() {
char buffer[1024];
int lineNum = 1, len;
FILE *fp;
fp = fopen("days_of_week.txt", "r");
while (1) {
memset(buffer, 0, sizeof(buffer));
fgets(buffer, sizeof(buffer), fp);
len = strlen(buffer);
if (len == 0 || buffer[len - 1] == '\0') {
break;
}
process(lineNum++, buffer);
}
fclose(fp);
return 0;
}
|
Maintain the same structure and functionality when rewriting this code in C#. | use strict;
use utf8;
binmode STDOUT, ":utf8";
sub auto_abbreviate {
my($string) = @_;
my @words = split ' ', $string;
my $max = 0;
return '' unless @words;
map { $max = length($_) if length($_) > $max } @words;
for $i (1..$max) {
my %seen;
return $i if @words == grep {!$seen{substr($_,0,$i)}++} @words;
}
return 'β';
}
open $fh, '<:encoding(UTF-8)', 'DoWAKA.txt';
while ($_ = <$fh>) {
print "$.) " . auto_abbreviate($_) . ' ' . $_;
}
| using System;
using System.Collections.Generic;
namespace Abbreviations {
class Program {
static void Main(string[] args) {
string[] lines = System.IO.File.ReadAllLines("days_of_week.txt");
int i = 0;
foreach (string line in lines) {
i++;
if (line.Length > 0) {
var days = line.Split();
if (days.Length != 7) {
throw new Exception("There aren't 7 days in line " + i);
}
Dictionary<string, int> temp = new Dictionary<string, int>();
foreach (string day in days) {
if (temp.ContainsKey(day)) {
Console.WriteLine(" β {0}", line);
continue;
}
temp.Add(day, 1);
}
int len = 1;
while (true) {
temp.Clear();
foreach(string day in days) {
string key;
if (len < day.Length) {
key = day.Substring(0, len);
} else {
key = day;
}
if (temp.ContainsKey(key)) {
break;
}
temp.Add(key, 1);
}
if (temp.Count == 7) {
Console.WriteLine("{0,2:D} {1}", len, line);
break;
}
len++;
}
}
}
}
}
}
|
Write the same code in C# as shown below in Perl. | use strict;
use utf8;
binmode STDOUT, ":utf8";
sub auto_abbreviate {
my($string) = @_;
my @words = split ' ', $string;
my $max = 0;
return '' unless @words;
map { $max = length($_) if length($_) > $max } @words;
for $i (1..$max) {
my %seen;
return $i if @words == grep {!$seen{substr($_,0,$i)}++} @words;
}
return 'β';
}
open $fh, '<:encoding(UTF-8)', 'DoWAKA.txt';
while ($_ = <$fh>) {
print "$.) " . auto_abbreviate($_) . ' ' . $_;
}
| using System;
using System.Collections.Generic;
namespace Abbreviations {
class Program {
static void Main(string[] args) {
string[] lines = System.IO.File.ReadAllLines("days_of_week.txt");
int i = 0;
foreach (string line in lines) {
i++;
if (line.Length > 0) {
var days = line.Split();
if (days.Length != 7) {
throw new Exception("There aren't 7 days in line " + i);
}
Dictionary<string, int> temp = new Dictionary<string, int>();
foreach (string day in days) {
if (temp.ContainsKey(day)) {
Console.WriteLine(" β {0}", line);
continue;
}
temp.Add(day, 1);
}
int len = 1;
while (true) {
temp.Clear();
foreach(string day in days) {
string key;
if (len < day.Length) {
key = day.Substring(0, len);
} else {
key = day;
}
if (temp.ContainsKey(key)) {
break;
}
temp.Add(key, 1);
}
if (temp.Count == 7) {
Console.WriteLine("{0,2:D} {1}", len, line);
break;
}
len++;
}
}
}
}
}
}
|
Change the following Perl code into C++ without altering its purpose. | use strict;
use utf8;
binmode STDOUT, ":utf8";
sub auto_abbreviate {
my($string) = @_;
my @words = split ' ', $string;
my $max = 0;
return '' unless @words;
map { $max = length($_) if length($_) > $max } @words;
for $i (1..$max) {
my %seen;
return $i if @words == grep {!$seen{substr($_,0,$i)}++} @words;
}
return 'β';
}
open $fh, '<:encoding(UTF-8)', 'DoWAKA.txt';
while ($_ = <$fh>) {
print "$.) " . auto_abbreviate($_) . ' ' . $_;
}
| #include <iomanip>
#include <iostream>
#include <fstream>
#include <map>
#include <sstream>
#include <string>
#include <vector>
std::vector<std::string> split(const std::string& str, char delimiter) {
std::vector<std::string> tokens;
std::string token;
std::istringstream tokenStream(str);
while (std::getline(tokenStream, token, delimiter)) {
tokens.push_back(token);
}
return tokens;
}
int main() {
using namespace std;
string line;
int i = 0;
ifstream in("days_of_week.txt");
if (in.is_open()) {
while (getline(in, line)) {
i++;
if (line.empty()) {
continue;
}
auto days = split(line, ' ');
if (days.size() != 7) {
throw std::runtime_error("There aren't 7 days in line " + i);
}
map<string, int> temp;
for (auto& day : days) {
if (temp.find(day) != temp.end()) {
cerr << " β " << line << '\n';
continue;
}
temp[day] = 1;
}
int len = 1;
while (true) {
temp.clear();
for (auto& day : days) {
string key = day.substr(0, len);
if (temp.find(key) != temp.end()) {
break;
}
temp[key] = 1;
}
if (temp.size() == 7) {
cout << setw(2) << len << " " << line << '\n';
break;
}
len++;
}
}
}
return 0;
}
|
Please provide an equivalent version of this Perl code in C++. | use strict;
use utf8;
binmode STDOUT, ":utf8";
sub auto_abbreviate {
my($string) = @_;
my @words = split ' ', $string;
my $max = 0;
return '' unless @words;
map { $max = length($_) if length($_) > $max } @words;
for $i (1..$max) {
my %seen;
return $i if @words == grep {!$seen{substr($_,0,$i)}++} @words;
}
return 'β';
}
open $fh, '<:encoding(UTF-8)', 'DoWAKA.txt';
while ($_ = <$fh>) {
print "$.) " . auto_abbreviate($_) . ' ' . $_;
}
| #include <iomanip>
#include <iostream>
#include <fstream>
#include <map>
#include <sstream>
#include <string>
#include <vector>
std::vector<std::string> split(const std::string& str, char delimiter) {
std::vector<std::string> tokens;
std::string token;
std::istringstream tokenStream(str);
while (std::getline(tokenStream, token, delimiter)) {
tokens.push_back(token);
}
return tokens;
}
int main() {
using namespace std;
string line;
int i = 0;
ifstream in("days_of_week.txt");
if (in.is_open()) {
while (getline(in, line)) {
i++;
if (line.empty()) {
continue;
}
auto days = split(line, ' ');
if (days.size() != 7) {
throw std::runtime_error("There aren't 7 days in line " + i);
}
map<string, int> temp;
for (auto& day : days) {
if (temp.find(day) != temp.end()) {
cerr << " β " << line << '\n';
continue;
}
temp[day] = 1;
}
int len = 1;
while (true) {
temp.clear();
for (auto& day : days) {
string key = day.substr(0, len);
if (temp.find(key) != temp.end()) {
break;
}
temp[key] = 1;
}
if (temp.size() == 7) {
cout << setw(2) << len << " " << line << '\n';
break;
}
len++;
}
}
}
return 0;
}
|
Produce a language-to-language conversion: from Perl to Java, same semantics. | use strict;
use utf8;
binmode STDOUT, ":utf8";
sub auto_abbreviate {
my($string) = @_;
my @words = split ' ', $string;
my $max = 0;
return '' unless @words;
map { $max = length($_) if length($_) > $max } @words;
for $i (1..$max) {
my %seen;
return $i if @words == grep {!$seen{substr($_,0,$i)}++} @words;
}
return 'β';
}
open $fh, '<:encoding(UTF-8)', 'DoWAKA.txt';
while ($_ = <$fh>) {
print "$.) " . auto_abbreviate($_) . ' ' . $_;
}
| import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class Abbreviations {
public static void main(String[] args) throws IOException {
Path path = Paths.get("days_of_week.txt");
List<String> readAllLines = Files.readAllLines(path);
for (int i = 0; i < readAllLines.size(); i++) {
String line = readAllLines.get(i);
if (line.length() == 0) continue;
String[] days = line.split(" ");
if (days.length != 7) throw new RuntimeException("There aren't 7 days on line " + (i + 1));
Map<String, Integer> temp = new HashMap<>();
for (String day : days) {
Integer count = temp.getOrDefault(day, 0);
temp.put(day, count + 1);
}
if (temp.size() < 7) {
System.out.print(" β ");
System.out.println(line);
continue;
}
int len = 1;
while (true) {
temp.clear();
for (String day : days) {
String sd;
if (len >= day.length()) {
sd = day;
} else {
sd = day.substring(0, len);
}
Integer count = temp.getOrDefault(sd, 0);
temp.put(sd, count + 1);
}
if (temp.size() == 7) {
System.out.printf("%2d %s\n", len, line);
break;
}
len++;
}
}
}
}
|
Transform the following Perl implementation into Java, maintaining the same output and logic. | use strict;
use utf8;
binmode STDOUT, ":utf8";
sub auto_abbreviate {
my($string) = @_;
my @words = split ' ', $string;
my $max = 0;
return '' unless @words;
map { $max = length($_) if length($_) > $max } @words;
for $i (1..$max) {
my %seen;
return $i if @words == grep {!$seen{substr($_,0,$i)}++} @words;
}
return 'β';
}
open $fh, '<:encoding(UTF-8)', 'DoWAKA.txt';
while ($_ = <$fh>) {
print "$.) " . auto_abbreviate($_) . ' ' . $_;
}
| import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class Abbreviations {
public static void main(String[] args) throws IOException {
Path path = Paths.get("days_of_week.txt");
List<String> readAllLines = Files.readAllLines(path);
for (int i = 0; i < readAllLines.size(); i++) {
String line = readAllLines.get(i);
if (line.length() == 0) continue;
String[] days = line.split(" ");
if (days.length != 7) throw new RuntimeException("There aren't 7 days on line " + (i + 1));
Map<String, Integer> temp = new HashMap<>();
for (String day : days) {
Integer count = temp.getOrDefault(day, 0);
temp.put(day, count + 1);
}
if (temp.size() < 7) {
System.out.print(" β ");
System.out.println(line);
continue;
}
int len = 1;
while (true) {
temp.clear();
for (String day : days) {
String sd;
if (len >= day.length()) {
sd = day;
} else {
sd = day.substring(0, len);
}
Integer count = temp.getOrDefault(sd, 0);
temp.put(sd, count + 1);
}
if (temp.size() == 7) {
System.out.printf("%2d %s\n", len, line);
break;
}
len++;
}
}
}
}
|
Generate an equivalent Python version of this Perl code. | use strict;
use utf8;
binmode STDOUT, ":utf8";
sub auto_abbreviate {
my($string) = @_;
my @words = split ' ', $string;
my $max = 0;
return '' unless @words;
map { $max = length($_) if length($_) > $max } @words;
for $i (1..$max) {
my %seen;
return $i if @words == grep {!$seen{substr($_,0,$i)}++} @words;
}
return 'β';
}
open $fh, '<:encoding(UTF-8)', 'DoWAKA.txt';
while ($_ = <$fh>) {
print "$.) " . auto_abbreviate($_) . ' ' . $_;
}
| def shortest_abbreviation_length(line, list_size):
words = line.split()
word_count = len(words)
if word_count != list_size:
raise ValueError(f'Not enough entries, expected {list_size} found {word_count}')
abbreviation_length = 1
abbreviations = set()
while(True):
abbreviations = {word[:abbreviation_length] for word in words}
if len(abbreviations) == list_size:
return abbreviation_length
abbreviation_length += 1
abbreviations.clear()
def automatic_abbreviations(filename, words_per_line):
with open(filename) as file:
for line in file:
line = line.rstrip()
if len(line) > 0:
length = shortest_abbreviation_length(line, words_per_line)
print(f'{length:2} {line}')
else:
print()
automatic_abbreviations('daysOfWeek.txt', 7)
|
Ensure the translated Python code behaves exactly like the original Perl snippet. | use strict;
use utf8;
binmode STDOUT, ":utf8";
sub auto_abbreviate {
my($string) = @_;
my @words = split ' ', $string;
my $max = 0;
return '' unless @words;
map { $max = length($_) if length($_) > $max } @words;
for $i (1..$max) {
my %seen;
return $i if @words == grep {!$seen{substr($_,0,$i)}++} @words;
}
return 'β';
}
open $fh, '<:encoding(UTF-8)', 'DoWAKA.txt';
while ($_ = <$fh>) {
print "$.) " . auto_abbreviate($_) . ' ' . $_;
}
| def shortest_abbreviation_length(line, list_size):
words = line.split()
word_count = len(words)
if word_count != list_size:
raise ValueError(f'Not enough entries, expected {list_size} found {word_count}')
abbreviation_length = 1
abbreviations = set()
while(True):
abbreviations = {word[:abbreviation_length] for word in words}
if len(abbreviations) == list_size:
return abbreviation_length
abbreviation_length += 1
abbreviations.clear()
def automatic_abbreviations(filename, words_per_line):
with open(filename) as file:
for line in file:
line = line.rstrip()
if len(line) > 0:
length = shortest_abbreviation_length(line, words_per_line)
print(f'{length:2} {line}')
else:
print()
automatic_abbreviations('daysOfWeek.txt', 7)
|
Convert this Perl snippet to VB and keep its semantics consistent. | use strict;
use utf8;
binmode STDOUT, ":utf8";
sub auto_abbreviate {
my($string) = @_;
my @words = split ' ', $string;
my $max = 0;
return '' unless @words;
map { $max = length($_) if length($_) > $max } @words;
for $i (1..$max) {
my %seen;
return $i if @words == grep {!$seen{substr($_,0,$i)}++} @words;
}
return 'β';
}
open $fh, '<:encoding(UTF-8)', 'DoWAKA.txt';
while ($_ = <$fh>) {
print "$.) " . auto_abbreviate($_) . ' ' . $_;
}
| Function MinimalLenght(strLine As String) As Integer
Dim myVar As Variant, I As Integer, Flag As Boolean, myColl As Collection, Count As Integer
myVar = Split(strLine, " ")
Count = 0
Do
Set myColl = New Collection
Count = Count + 1
On Error Resume Next
Do
myColl.Add Left$(myVar(I), Count), Left$(myVar(I), Count)
I = I + 1
Loop While Err.Number = 0 And I <= UBound(myVar)
Flag = Err.Number = 0
On Error GoTo 0
I = 0
Set myColl = Nothing
Loop While Not Flag
MinimalLenght = Count
End Function
|
Change the following Perl code into VB without altering its purpose. | use strict;
use utf8;
binmode STDOUT, ":utf8";
sub auto_abbreviate {
my($string) = @_;
my @words = split ' ', $string;
my $max = 0;
return '' unless @words;
map { $max = length($_) if length($_) > $max } @words;
for $i (1..$max) {
my %seen;
return $i if @words == grep {!$seen{substr($_,0,$i)}++} @words;
}
return 'β';
}
open $fh, '<:encoding(UTF-8)', 'DoWAKA.txt';
while ($_ = <$fh>) {
print "$.) " . auto_abbreviate($_) . ' ' . $_;
}
| Function MinimalLenght(strLine As String) As Integer
Dim myVar As Variant, I As Integer, Flag As Boolean, myColl As Collection, Count As Integer
myVar = Split(strLine, " ")
Count = 0
Do
Set myColl = New Collection
Count = Count + 1
On Error Resume Next
Do
myColl.Add Left$(myVar(I), Count), Left$(myVar(I), Count)
I = I + 1
Loop While Err.Number = 0 And I <= UBound(myVar)
Flag = Err.Number = 0
On Error GoTo 0
I = 0
Set myColl = Nothing
Loop While Not Flag
MinimalLenght = Count
End Function
|
Write the same algorithm in Go as shown in this Perl implementation. | use strict;
use utf8;
binmode STDOUT, ":utf8";
sub auto_abbreviate {
my($string) = @_;
my @words = split ' ', $string;
my $max = 0;
return '' unless @words;
map { $max = length($_) if length($_) > $max } @words;
for $i (1..$max) {
my %seen;
return $i if @words == grep {!$seen{substr($_,0,$i)}++} @words;
}
return 'β';
}
open $fh, '<:encoding(UTF-8)', 'DoWAKA.txt';
while ($_ = <$fh>) {
print "$.) " . auto_abbreviate($_) . ' ' . $_;
}
| package main
import(
"bufio"
"fmt"
"os"
"strings"
)
func distinctStrings(strs []string) []string {
len := len(strs)
set := make(map[string]bool, len)
distinct := make([]string, 0, len)
for _, str := range strs {
if !set[str] {
distinct = append(distinct, str)
set[str] = true
}
}
return distinct
}
func takeRunes(s string, n int) string {
i := 0
for j := range s {
if i == n {
return s[:j]
}
i++
}
return s
}
func main() {
file, err := os.Open("days_of_week.txt")
if err != nil {
fmt.Println("Unable to open file.")
return
}
defer file.Close()
reader := bufio.NewReader(file)
lineCount := 0
for {
line, err := reader.ReadString('\n')
if err != nil {
return
}
line = strings.TrimSpace(line)
lineCount++
if line == "" {
fmt.Println()
continue
}
days := strings.Fields(line)
daysLen := len(days)
if (len(days) != 7) {
fmt.Println("There aren't 7 days in line", lineCount)
return
}
if len(distinctStrings(days)) != 7 {
fmt.Println(" β ", line)
continue
}
for abbrevLen := 1; ; abbrevLen++ {
abbrevs := make([]string, daysLen)
for i := 0; i < daysLen; i++ {
abbrevs[i] = takeRunes(days[i], abbrevLen)
}
if len(distinctStrings(abbrevs)) == 7 {
fmt.Printf("%2d %s\n", abbrevLen, line)
break
}
}
}
}
|
Translate this program into Go but keep the logic exactly as in Perl. | use strict;
use utf8;
binmode STDOUT, ":utf8";
sub auto_abbreviate {
my($string) = @_;
my @words = split ' ', $string;
my $max = 0;
return '' unless @words;
map { $max = length($_) if length($_) > $max } @words;
for $i (1..$max) {
my %seen;
return $i if @words == grep {!$seen{substr($_,0,$i)}++} @words;
}
return 'β';
}
open $fh, '<:encoding(UTF-8)', 'DoWAKA.txt';
while ($_ = <$fh>) {
print "$.) " . auto_abbreviate($_) . ' ' . $_;
}
| package main
import(
"bufio"
"fmt"
"os"
"strings"
)
func distinctStrings(strs []string) []string {
len := len(strs)
set := make(map[string]bool, len)
distinct := make([]string, 0, len)
for _, str := range strs {
if !set[str] {
distinct = append(distinct, str)
set[str] = true
}
}
return distinct
}
func takeRunes(s string, n int) string {
i := 0
for j := range s {
if i == n {
return s[:j]
}
i++
}
return s
}
func main() {
file, err := os.Open("days_of_week.txt")
if err != nil {
fmt.Println("Unable to open file.")
return
}
defer file.Close()
reader := bufio.NewReader(file)
lineCount := 0
for {
line, err := reader.ReadString('\n')
if err != nil {
return
}
line = strings.TrimSpace(line)
lineCount++
if line == "" {
fmt.Println()
continue
}
days := strings.Fields(line)
daysLen := len(days)
if (len(days) != 7) {
fmt.Println("There aren't 7 days in line", lineCount)
return
}
if len(distinctStrings(days)) != 7 {
fmt.Println(" β ", line)
continue
}
for abbrevLen := 1; ; abbrevLen++ {
abbrevs := make([]string, daysLen)
for i := 0; i < daysLen; i++ {
abbrevs[i] = takeRunes(days[i], abbrevLen)
}
if len(distinctStrings(abbrevs)) == 7 {
fmt.Printf("%2d %s\n", abbrevLen, line)
break
}
}
}
}
|
Write the same algorithm in C as shown in this Racket implementation. | #lang racket
(require racket/set)
(define (abbr-length ss)
(for*/first ((l (in-range 1 (string-length (argmax string-length ss))))
#:when (equal? (sequence-length
(for/set ((s ss))
(substring s 0 (min l (string-length s)))))
(length ss)))
l))
(module+ main
(define report-line
(match-lambda
["" ""]
[(and s (app string-split ss)) (format "~a ~a" (abbr-length ss) s)]))
(for-each (compose displayln report-line) (take (file->lines "data.txt") 5)))
| #include <stdio.h>
#include <stdlib.h>
#include <string.h>
void process(int lineNum, char buffer[]) {
char days[7][64];
int i = 0, d = 0, j = 0;
while (buffer[i] != 0) {
if (buffer[i] == ' ') {
days[d][j] = '\0';
++d;
j = 0;
} else if (buffer[i] == '\n' || buffer[i] == '\r') {
days[d][j] = '\0';
++d;
break;
} else {
days[d][j] = buffer[i];
++j;
}
if (d >= 7) {
printf("There aren't 7 days in line %d\n", lineNum);
return;
}
++i;
}
if (buffer[i] == '\0') {
days[d][j] = '\0';
++d;
}
if (d < 7) {
printf("There aren't 7 days in line %d\n", lineNum);
return;
} else {
int len = 0;
for (len = 1; len < 64; ++len) {
int d1;
for (d1 = 0; d1 < 7; ++d1) {
int d2;
for (d2 = d1 + 1; d2 < 7; ++d2) {
int unique = 0;
for (i = 0; i < len; ++i) {
if (days[d1][i] != days[d2][i]) {
unique = 1;
break;
}
}
if (!unique) {
goto next_length;
}
}
}
printf("%2d ", len);
for (i = 0; i < 7; ++i) {
printf(" %s", days[i]);
}
printf("\n");
return;
next_length: {}
}
}
printf("Failed to find uniqueness within the bounds.");
}
int main() {
char buffer[1024];
int lineNum = 1, len;
FILE *fp;
fp = fopen("days_of_week.txt", "r");
while (1) {
memset(buffer, 0, sizeof(buffer));
fgets(buffer, sizeof(buffer), fp);
len = strlen(buffer);
if (len == 0 || buffer[len - 1] == '\0') {
break;
}
process(lineNum++, buffer);
}
fclose(fp);
return 0;
}
|
Write the same algorithm in C as shown in this Racket implementation. | #lang racket
(require racket/set)
(define (abbr-length ss)
(for*/first ((l (in-range 1 (string-length (argmax string-length ss))))
#:when (equal? (sequence-length
(for/set ((s ss))
(substring s 0 (min l (string-length s)))))
(length ss)))
l))
(module+ main
(define report-line
(match-lambda
["" ""]
[(and s (app string-split ss)) (format "~a ~a" (abbr-length ss) s)]))
(for-each (compose displayln report-line) (take (file->lines "data.txt") 5)))
| #include <stdio.h>
#include <stdlib.h>
#include <string.h>
void process(int lineNum, char buffer[]) {
char days[7][64];
int i = 0, d = 0, j = 0;
while (buffer[i] != 0) {
if (buffer[i] == ' ') {
days[d][j] = '\0';
++d;
j = 0;
} else if (buffer[i] == '\n' || buffer[i] == '\r') {
days[d][j] = '\0';
++d;
break;
} else {
days[d][j] = buffer[i];
++j;
}
if (d >= 7) {
printf("There aren't 7 days in line %d\n", lineNum);
return;
}
++i;
}
if (buffer[i] == '\0') {
days[d][j] = '\0';
++d;
}
if (d < 7) {
printf("There aren't 7 days in line %d\n", lineNum);
return;
} else {
int len = 0;
for (len = 1; len < 64; ++len) {
int d1;
for (d1 = 0; d1 < 7; ++d1) {
int d2;
for (d2 = d1 + 1; d2 < 7; ++d2) {
int unique = 0;
for (i = 0; i < len; ++i) {
if (days[d1][i] != days[d2][i]) {
unique = 1;
break;
}
}
if (!unique) {
goto next_length;
}
}
}
printf("%2d ", len);
for (i = 0; i < 7; ++i) {
printf(" %s", days[i]);
}
printf("\n");
return;
next_length: {}
}
}
printf("Failed to find uniqueness within the bounds.");
}
int main() {
char buffer[1024];
int lineNum = 1, len;
FILE *fp;
fp = fopen("days_of_week.txt", "r");
while (1) {
memset(buffer, 0, sizeof(buffer));
fgets(buffer, sizeof(buffer), fp);
len = strlen(buffer);
if (len == 0 || buffer[len - 1] == '\0') {
break;
}
process(lineNum++, buffer);
}
fclose(fp);
return 0;
}
|
Convert the following code from Racket to C#, ensuring the logic remains intact. | #lang racket
(require racket/set)
(define (abbr-length ss)
(for*/first ((l (in-range 1 (string-length (argmax string-length ss))))
#:when (equal? (sequence-length
(for/set ((s ss))
(substring s 0 (min l (string-length s)))))
(length ss)))
l))
(module+ main
(define report-line
(match-lambda
["" ""]
[(and s (app string-split ss)) (format "~a ~a" (abbr-length ss) s)]))
(for-each (compose displayln report-line) (take (file->lines "data.txt") 5)))
| using System;
using System.Collections.Generic;
namespace Abbreviations {
class Program {
static void Main(string[] args) {
string[] lines = System.IO.File.ReadAllLines("days_of_week.txt");
int i = 0;
foreach (string line in lines) {
i++;
if (line.Length > 0) {
var days = line.Split();
if (days.Length != 7) {
throw new Exception("There aren't 7 days in line " + i);
}
Dictionary<string, int> temp = new Dictionary<string, int>();
foreach (string day in days) {
if (temp.ContainsKey(day)) {
Console.WriteLine(" β {0}", line);
continue;
}
temp.Add(day, 1);
}
int len = 1;
while (true) {
temp.Clear();
foreach(string day in days) {
string key;
if (len < day.Length) {
key = day.Substring(0, len);
} else {
key = day;
}
if (temp.ContainsKey(key)) {
break;
}
temp.Add(key, 1);
}
if (temp.Count == 7) {
Console.WriteLine("{0,2:D} {1}", len, line);
break;
}
len++;
}
}
}
}
}
}
|
Write a version of this Racket function in C# with identical behavior. | #lang racket
(require racket/set)
(define (abbr-length ss)
(for*/first ((l (in-range 1 (string-length (argmax string-length ss))))
#:when (equal? (sequence-length
(for/set ((s ss))
(substring s 0 (min l (string-length s)))))
(length ss)))
l))
(module+ main
(define report-line
(match-lambda
["" ""]
[(and s (app string-split ss)) (format "~a ~a" (abbr-length ss) s)]))
(for-each (compose displayln report-line) (take (file->lines "data.txt") 5)))
| using System;
using System.Collections.Generic;
namespace Abbreviations {
class Program {
static void Main(string[] args) {
string[] lines = System.IO.File.ReadAllLines("days_of_week.txt");
int i = 0;
foreach (string line in lines) {
i++;
if (line.Length > 0) {
var days = line.Split();
if (days.Length != 7) {
throw new Exception("There aren't 7 days in line " + i);
}
Dictionary<string, int> temp = new Dictionary<string, int>();
foreach (string day in days) {
if (temp.ContainsKey(day)) {
Console.WriteLine(" β {0}", line);
continue;
}
temp.Add(day, 1);
}
int len = 1;
while (true) {
temp.Clear();
foreach(string day in days) {
string key;
if (len < day.Length) {
key = day.Substring(0, len);
} else {
key = day;
}
if (temp.ContainsKey(key)) {
break;
}
temp.Add(key, 1);
}
if (temp.Count == 7) {
Console.WriteLine("{0,2:D} {1}", len, line);
break;
}
len++;
}
}
}
}
}
}
|
Write a version of this Racket function in C++ with identical behavior. | #lang racket
(require racket/set)
(define (abbr-length ss)
(for*/first ((l (in-range 1 (string-length (argmax string-length ss))))
#:when (equal? (sequence-length
(for/set ((s ss))
(substring s 0 (min l (string-length s)))))
(length ss)))
l))
(module+ main
(define report-line
(match-lambda
["" ""]
[(and s (app string-split ss)) (format "~a ~a" (abbr-length ss) s)]))
(for-each (compose displayln report-line) (take (file->lines "data.txt") 5)))
| #include <iomanip>
#include <iostream>
#include <fstream>
#include <map>
#include <sstream>
#include <string>
#include <vector>
std::vector<std::string> split(const std::string& str, char delimiter) {
std::vector<std::string> tokens;
std::string token;
std::istringstream tokenStream(str);
while (std::getline(tokenStream, token, delimiter)) {
tokens.push_back(token);
}
return tokens;
}
int main() {
using namespace std;
string line;
int i = 0;
ifstream in("days_of_week.txt");
if (in.is_open()) {
while (getline(in, line)) {
i++;
if (line.empty()) {
continue;
}
auto days = split(line, ' ');
if (days.size() != 7) {
throw std::runtime_error("There aren't 7 days in line " + i);
}
map<string, int> temp;
for (auto& day : days) {
if (temp.find(day) != temp.end()) {
cerr << " β " << line << '\n';
continue;
}
temp[day] = 1;
}
int len = 1;
while (true) {
temp.clear();
for (auto& day : days) {
string key = day.substr(0, len);
if (temp.find(key) != temp.end()) {
break;
}
temp[key] = 1;
}
if (temp.size() == 7) {
cout << setw(2) << len << " " << line << '\n';
break;
}
len++;
}
}
}
return 0;
}
|
Produce a functionally identical C++ code for the snippet given in Racket. | #lang racket
(require racket/set)
(define (abbr-length ss)
(for*/first ((l (in-range 1 (string-length (argmax string-length ss))))
#:when (equal? (sequence-length
(for/set ((s ss))
(substring s 0 (min l (string-length s)))))
(length ss)))
l))
(module+ main
(define report-line
(match-lambda
["" ""]
[(and s (app string-split ss)) (format "~a ~a" (abbr-length ss) s)]))
(for-each (compose displayln report-line) (take (file->lines "data.txt") 5)))
| #include <iomanip>
#include <iostream>
#include <fstream>
#include <map>
#include <sstream>
#include <string>
#include <vector>
std::vector<std::string> split(const std::string& str, char delimiter) {
std::vector<std::string> tokens;
std::string token;
std::istringstream tokenStream(str);
while (std::getline(tokenStream, token, delimiter)) {
tokens.push_back(token);
}
return tokens;
}
int main() {
using namespace std;
string line;
int i = 0;
ifstream in("days_of_week.txt");
if (in.is_open()) {
while (getline(in, line)) {
i++;
if (line.empty()) {
continue;
}
auto days = split(line, ' ');
if (days.size() != 7) {
throw std::runtime_error("There aren't 7 days in line " + i);
}
map<string, int> temp;
for (auto& day : days) {
if (temp.find(day) != temp.end()) {
cerr << " β " << line << '\n';
continue;
}
temp[day] = 1;
}
int len = 1;
while (true) {
temp.clear();
for (auto& day : days) {
string key = day.substr(0, len);
if (temp.find(key) != temp.end()) {
break;
}
temp[key] = 1;
}
if (temp.size() == 7) {
cout << setw(2) << len << " " << line << '\n';
break;
}
len++;
}
}
}
return 0;
}
|
Convert this Racket snippet to Java and keep its semantics consistent. | #lang racket
(require racket/set)
(define (abbr-length ss)
(for*/first ((l (in-range 1 (string-length (argmax string-length ss))))
#:when (equal? (sequence-length
(for/set ((s ss))
(substring s 0 (min l (string-length s)))))
(length ss)))
l))
(module+ main
(define report-line
(match-lambda
["" ""]
[(and s (app string-split ss)) (format "~a ~a" (abbr-length ss) s)]))
(for-each (compose displayln report-line) (take (file->lines "data.txt") 5)))
| import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class Abbreviations {
public static void main(String[] args) throws IOException {
Path path = Paths.get("days_of_week.txt");
List<String> readAllLines = Files.readAllLines(path);
for (int i = 0; i < readAllLines.size(); i++) {
String line = readAllLines.get(i);
if (line.length() == 0) continue;
String[] days = line.split(" ");
if (days.length != 7) throw new RuntimeException("There aren't 7 days on line " + (i + 1));
Map<String, Integer> temp = new HashMap<>();
for (String day : days) {
Integer count = temp.getOrDefault(day, 0);
temp.put(day, count + 1);
}
if (temp.size() < 7) {
System.out.print(" β ");
System.out.println(line);
continue;
}
int len = 1;
while (true) {
temp.clear();
for (String day : days) {
String sd;
if (len >= day.length()) {
sd = day;
} else {
sd = day.substring(0, len);
}
Integer count = temp.getOrDefault(sd, 0);
temp.put(sd, count + 1);
}
if (temp.size() == 7) {
System.out.printf("%2d %s\n", len, line);
break;
}
len++;
}
}
}
}
|
Port the following code from Racket to Java with equivalent syntax and logic. | #lang racket
(require racket/set)
(define (abbr-length ss)
(for*/first ((l (in-range 1 (string-length (argmax string-length ss))))
#:when (equal? (sequence-length
(for/set ((s ss))
(substring s 0 (min l (string-length s)))))
(length ss)))
l))
(module+ main
(define report-line
(match-lambda
["" ""]
[(and s (app string-split ss)) (format "~a ~a" (abbr-length ss) s)]))
(for-each (compose displayln report-line) (take (file->lines "data.txt") 5)))
| import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class Abbreviations {
public static void main(String[] args) throws IOException {
Path path = Paths.get("days_of_week.txt");
List<String> readAllLines = Files.readAllLines(path);
for (int i = 0; i < readAllLines.size(); i++) {
String line = readAllLines.get(i);
if (line.length() == 0) continue;
String[] days = line.split(" ");
if (days.length != 7) throw new RuntimeException("There aren't 7 days on line " + (i + 1));
Map<String, Integer> temp = new HashMap<>();
for (String day : days) {
Integer count = temp.getOrDefault(day, 0);
temp.put(day, count + 1);
}
if (temp.size() < 7) {
System.out.print(" β ");
System.out.println(line);
continue;
}
int len = 1;
while (true) {
temp.clear();
for (String day : days) {
String sd;
if (len >= day.length()) {
sd = day;
} else {
sd = day.substring(0, len);
}
Integer count = temp.getOrDefault(sd, 0);
temp.put(sd, count + 1);
}
if (temp.size() == 7) {
System.out.printf("%2d %s\n", len, line);
break;
}
len++;
}
}
}
}
|
Translate the given Racket code snippet into Python without altering its behavior. | #lang racket
(require racket/set)
(define (abbr-length ss)
(for*/first ((l (in-range 1 (string-length (argmax string-length ss))))
#:when (equal? (sequence-length
(for/set ((s ss))
(substring s 0 (min l (string-length s)))))
(length ss)))
l))
(module+ main
(define report-line
(match-lambda
["" ""]
[(and s (app string-split ss)) (format "~a ~a" (abbr-length ss) s)]))
(for-each (compose displayln report-line) (take (file->lines "data.txt") 5)))
| def shortest_abbreviation_length(line, list_size):
words = line.split()
word_count = len(words)
if word_count != list_size:
raise ValueError(f'Not enough entries, expected {list_size} found {word_count}')
abbreviation_length = 1
abbreviations = set()
while(True):
abbreviations = {word[:abbreviation_length] for word in words}
if len(abbreviations) == list_size:
return abbreviation_length
abbreviation_length += 1
abbreviations.clear()
def automatic_abbreviations(filename, words_per_line):
with open(filename) as file:
for line in file:
line = line.rstrip()
if len(line) > 0:
length = shortest_abbreviation_length(line, words_per_line)
print(f'{length:2} {line}')
else:
print()
automatic_abbreviations('daysOfWeek.txt', 7)
|
Produce a language-to-language conversion: from Racket to Python, same semantics. | #lang racket
(require racket/set)
(define (abbr-length ss)
(for*/first ((l (in-range 1 (string-length (argmax string-length ss))))
#:when (equal? (sequence-length
(for/set ((s ss))
(substring s 0 (min l (string-length s)))))
(length ss)))
l))
(module+ main
(define report-line
(match-lambda
["" ""]
[(and s (app string-split ss)) (format "~a ~a" (abbr-length ss) s)]))
(for-each (compose displayln report-line) (take (file->lines "data.txt") 5)))
| def shortest_abbreviation_length(line, list_size):
words = line.split()
word_count = len(words)
if word_count != list_size:
raise ValueError(f'Not enough entries, expected {list_size} found {word_count}')
abbreviation_length = 1
abbreviations = set()
while(True):
abbreviations = {word[:abbreviation_length] for word in words}
if len(abbreviations) == list_size:
return abbreviation_length
abbreviation_length += 1
abbreviations.clear()
def automatic_abbreviations(filename, words_per_line):
with open(filename) as file:
for line in file:
line = line.rstrip()
if len(line) > 0:
length = shortest_abbreviation_length(line, words_per_line)
print(f'{length:2} {line}')
else:
print()
automatic_abbreviations('daysOfWeek.txt', 7)
|
Change the following Racket code into VB without altering its purpose. | #lang racket
(require racket/set)
(define (abbr-length ss)
(for*/first ((l (in-range 1 (string-length (argmax string-length ss))))
#:when (equal? (sequence-length
(for/set ((s ss))
(substring s 0 (min l (string-length s)))))
(length ss)))
l))
(module+ main
(define report-line
(match-lambda
["" ""]
[(and s (app string-split ss)) (format "~a ~a" (abbr-length ss) s)]))
(for-each (compose displayln report-line) (take (file->lines "data.txt") 5)))
| Function MinimalLenght(strLine As String) As Integer
Dim myVar As Variant, I As Integer, Flag As Boolean, myColl As Collection, Count As Integer
myVar = Split(strLine, " ")
Count = 0
Do
Set myColl = New Collection
Count = Count + 1
On Error Resume Next
Do
myColl.Add Left$(myVar(I), Count), Left$(myVar(I), Count)
I = I + 1
Loop While Err.Number = 0 And I <= UBound(myVar)
Flag = Err.Number = 0
On Error GoTo 0
I = 0
Set myColl = Nothing
Loop While Not Flag
MinimalLenght = Count
End Function
|
Write a version of this Racket function in VB with identical behavior. | #lang racket
(require racket/set)
(define (abbr-length ss)
(for*/first ((l (in-range 1 (string-length (argmax string-length ss))))
#:when (equal? (sequence-length
(for/set ((s ss))
(substring s 0 (min l (string-length s)))))
(length ss)))
l))
(module+ main
(define report-line
(match-lambda
["" ""]
[(and s (app string-split ss)) (format "~a ~a" (abbr-length ss) s)]))
(for-each (compose displayln report-line) (take (file->lines "data.txt") 5)))
| Function MinimalLenght(strLine As String) As Integer
Dim myVar As Variant, I As Integer, Flag As Boolean, myColl As Collection, Count As Integer
myVar = Split(strLine, " ")
Count = 0
Do
Set myColl = New Collection
Count = Count + 1
On Error Resume Next
Do
myColl.Add Left$(myVar(I), Count), Left$(myVar(I), Count)
I = I + 1
Loop While Err.Number = 0 And I <= UBound(myVar)
Flag = Err.Number = 0
On Error GoTo 0
I = 0
Set myColl = Nothing
Loop While Not Flag
MinimalLenght = Count
End Function
|
Can you help me rewrite this code in Go instead of Racket, keeping it the same logically? | #lang racket
(require racket/set)
(define (abbr-length ss)
(for*/first ((l (in-range 1 (string-length (argmax string-length ss))))
#:when (equal? (sequence-length
(for/set ((s ss))
(substring s 0 (min l (string-length s)))))
(length ss)))
l))
(module+ main
(define report-line
(match-lambda
["" ""]
[(and s (app string-split ss)) (format "~a ~a" (abbr-length ss) s)]))
(for-each (compose displayln report-line) (take (file->lines "data.txt") 5)))
| package main
import(
"bufio"
"fmt"
"os"
"strings"
)
func distinctStrings(strs []string) []string {
len := len(strs)
set := make(map[string]bool, len)
distinct := make([]string, 0, len)
for _, str := range strs {
if !set[str] {
distinct = append(distinct, str)
set[str] = true
}
}
return distinct
}
func takeRunes(s string, n int) string {
i := 0
for j := range s {
if i == n {
return s[:j]
}
i++
}
return s
}
func main() {
file, err := os.Open("days_of_week.txt")
if err != nil {
fmt.Println("Unable to open file.")
return
}
defer file.Close()
reader := bufio.NewReader(file)
lineCount := 0
for {
line, err := reader.ReadString('\n')
if err != nil {
return
}
line = strings.TrimSpace(line)
lineCount++
if line == "" {
fmt.Println()
continue
}
days := strings.Fields(line)
daysLen := len(days)
if (len(days) != 7) {
fmt.Println("There aren't 7 days in line", lineCount)
return
}
if len(distinctStrings(days)) != 7 {
fmt.Println(" β ", line)
continue
}
for abbrevLen := 1; ; abbrevLen++ {
abbrevs := make([]string, daysLen)
for i := 0; i < daysLen; i++ {
abbrevs[i] = takeRunes(days[i], abbrevLen)
}
if len(distinctStrings(abbrevs)) == 7 {
fmt.Printf("%2d %s\n", abbrevLen, line)
break
}
}
}
}
|
Produce a functionally identical Go code for the snippet given in Racket. | #lang racket
(require racket/set)
(define (abbr-length ss)
(for*/first ((l (in-range 1 (string-length (argmax string-length ss))))
#:when (equal? (sequence-length
(for/set ((s ss))
(substring s 0 (min l (string-length s)))))
(length ss)))
l))
(module+ main
(define report-line
(match-lambda
["" ""]
[(and s (app string-split ss)) (format "~a ~a" (abbr-length ss) s)]))
(for-each (compose displayln report-line) (take (file->lines "data.txt") 5)))
| package main
import(
"bufio"
"fmt"
"os"
"strings"
)
func distinctStrings(strs []string) []string {
len := len(strs)
set := make(map[string]bool, len)
distinct := make([]string, 0, len)
for _, str := range strs {
if !set[str] {
distinct = append(distinct, str)
set[str] = true
}
}
return distinct
}
func takeRunes(s string, n int) string {
i := 0
for j := range s {
if i == n {
return s[:j]
}
i++
}
return s
}
func main() {
file, err := os.Open("days_of_week.txt")
if err != nil {
fmt.Println("Unable to open file.")
return
}
defer file.Close()
reader := bufio.NewReader(file)
lineCount := 0
for {
line, err := reader.ReadString('\n')
if err != nil {
return
}
line = strings.TrimSpace(line)
lineCount++
if line == "" {
fmt.Println()
continue
}
days := strings.Fields(line)
daysLen := len(days)
if (len(days) != 7) {
fmt.Println("There aren't 7 days in line", lineCount)
return
}
if len(distinctStrings(days)) != 7 {
fmt.Println(" β ", line)
continue
}
for abbrevLen := 1; ; abbrevLen++ {
abbrevs := make([]string, daysLen)
for i := 0; i < daysLen; i++ {
abbrevs[i] = takeRunes(days[i], abbrevLen)
}
if len(distinctStrings(abbrevs)) == 7 {
fmt.Printf("%2d %s\n", abbrevLen, line)
break
}
}
}
}
|
Preserve the algorithm and functionality while converting the code from COBOL to C. | IDENTIFICATION DIVISION.
PROGRAM-ID. AUTO-ABBREVIATIONS.
ENVIRONMENT DIVISION.
INPUT-OUTPUT SECTION.
FILE-CONTROL.
SELECT DOW ASSIGN TO "days-of-week.txt"
ORGANIZATION IS LINE SEQUENTIAL.
DATA DIVISION.
FILE SECTION.
FD DOW.
01 DOW-FILE PIC X(200).
WORKING-STORAGE SECTION.
01 DOW-LINE PIC X(200).
01 ENDO PIC 9(1).
01 ENDO2 PIC 9(1).
01 CURDAY PIC X(50).
01 ABPTR PIC 999.
01 LINE-NUM PIC 9(3) VALUE 1.
01 CHARAMT PIC 9(3) VALUE 1.
01 LARGESTCHARAMT PIC 9(3).
01 DAYNUM PIC 9(3) VALUE 1.
01 ABRESTART PIC 9(1).
01 CURABBR PIC X(50).
01 TMP1 PIC 9(3).
01 TMP2 PIC 9(3).
01 TINDEX PIC 9(3) VALUE 1.
01 ABBRLIST.
05 ABBRITEM PIC X(50) OCCURS 7 TIMES.
PROCEDURE DIVISION.
OPEN INPUT DOW.
PERFORM UNTIL ENDO = 1
READ DOW INTO DOW-LINE
AT END MOVE 1 TO ENDO
NOT AT END PERFORM
IF DOW-LINE = "" THEN
DISPLAY ""
ELSE
MOVE 0 TO ENDO2
MOVE 0 TO CHARAMT
PERFORM UNTIL ENDO2 > 0
MOVE 1 TO ABPTR
MOVE 1 TO DAYNUM
MOVE 0 TO ABRESTART
ADD 1 TO CHARAMT
MOVE 1 TO TINDEX
PERFORM 7 TIMES
MOVE SPACE TO ABBRITEM(TINDEX)
ADD 1 TO TINDEX
END-PERFORM
PERFORM 7 TIMES
UNSTRING DOW-LINE DELIMITED BY SPACE
INTO CURDAY
WITH POINTER ABPTR
END-UNSTRING
MOVE 0 TO TMP1
MOVE 0 TO TMP2
INSPECT CURDAY
TALLYING TMP1 FOR ALL CHARACTERS
INSPECT CURDAY
TALLYING TMP2 FOR ALL SPACE
SUBTRACT TMP2 FROM TMP1
IF TMP1 > LARGESTCHARAMT THEN
MOVE TMP1 TO LARGESTCHARAMT
END-IF
IF CURDAY = "" THEN
MOVE 3 TO ENDO2
END-IF
MOVE CURDAY(1:CHARAMT) TO CURABBR
MOVE 1 TO TINDEX
PERFORM 7 TIMES
IF ABBRITEM(TINDEX) = CURABBR THEN
MOVE 1 TO ABRESTART
END-IF
ADD 1 TO TINDEX
END-PERFORM
MOVE CURABBR TO ABBRITEM(DAYNUM)
ADD 1 TO DAYNUM
END-PERFORM
IF ABRESTART = 0 THEN
MOVE 1 TO ENDO2
END-IF
IF CHARAMT > LARGESTCHARAMT THEN
MOVE 2 TO ENDO2
END-IF
END-PERFORM
DISPLAY "Line " LINE-NUM ": " WITH NO ADVANCING
IF ENDO2 = 3 THEN
DISPLAY "Error: not enough " WITH NO ADVANCING
DISPLAY "days"
ELSE IF ENDO2 = 2 THEN
DISPLAY "Error: identical " WITH NO ADVANCING
DISPLAY "days"
ELSE
DISPLAY CHARAMT ": " WITH NO ADVANCING
MOVE 1 TO TINDEX
PERFORM 7 TIMES
MOVE ABBRITEM(TINDEX) TO CURABBR
MOVE 0 TO TMP1
MOVE 0 TO TMP2
INSPECT CURABBR
TALLYING TMP1 FOR ALL CHARACTERS
INSPECT CURABBR
TALLYING TMP2 FOR TRAILING SPACES
SUBTRACT TMP2 FROM TMP1
DISPLAY CURABBR(1:TMP1) WITH NO ADVANCING
DISPLAY "." WITH NO ADVANCING
IF TINDEX < 7 THEN
DISPLAY SPACE WITH NO ADVANCING
ELSE
DISPLAY X"0a" WITH NO ADVANCING
END-IF
ADD 1 TO TINDEX
END-PERFORM
END-IF
END-IF
END-PERFORM
END-READ
ADD 1 TO LINE-NUM
END-PERFORM.
CLOSE DOW.
STOP RUN.
| #include <stdio.h>
#include <stdlib.h>
#include <string.h>
void process(int lineNum, char buffer[]) {
char days[7][64];
int i = 0, d = 0, j = 0;
while (buffer[i] != 0) {
if (buffer[i] == ' ') {
days[d][j] = '\0';
++d;
j = 0;
} else if (buffer[i] == '\n' || buffer[i] == '\r') {
days[d][j] = '\0';
++d;
break;
} else {
days[d][j] = buffer[i];
++j;
}
if (d >= 7) {
printf("There aren't 7 days in line %d\n", lineNum);
return;
}
++i;
}
if (buffer[i] == '\0') {
days[d][j] = '\0';
++d;
}
if (d < 7) {
printf("There aren't 7 days in line %d\n", lineNum);
return;
} else {
int len = 0;
for (len = 1; len < 64; ++len) {
int d1;
for (d1 = 0; d1 < 7; ++d1) {
int d2;
for (d2 = d1 + 1; d2 < 7; ++d2) {
int unique = 0;
for (i = 0; i < len; ++i) {
if (days[d1][i] != days[d2][i]) {
unique = 1;
break;
}
}
if (!unique) {
goto next_length;
}
}
}
printf("%2d ", len);
for (i = 0; i < 7; ++i) {
printf(" %s", days[i]);
}
printf("\n");
return;
next_length: {}
}
}
printf("Failed to find uniqueness within the bounds.");
}
int main() {
char buffer[1024];
int lineNum = 1, len;
FILE *fp;
fp = fopen("days_of_week.txt", "r");
while (1) {
memset(buffer, 0, sizeof(buffer));
fgets(buffer, sizeof(buffer), fp);
len = strlen(buffer);
if (len == 0 || buffer[len - 1] == '\0') {
break;
}
process(lineNum++, buffer);
}
fclose(fp);
return 0;
}
|
Convert this COBOL block to C, preserving its control flow and logic. | IDENTIFICATION DIVISION.
PROGRAM-ID. AUTO-ABBREVIATIONS.
ENVIRONMENT DIVISION.
INPUT-OUTPUT SECTION.
FILE-CONTROL.
SELECT DOW ASSIGN TO "days-of-week.txt"
ORGANIZATION IS LINE SEQUENTIAL.
DATA DIVISION.
FILE SECTION.
FD DOW.
01 DOW-FILE PIC X(200).
WORKING-STORAGE SECTION.
01 DOW-LINE PIC X(200).
01 ENDO PIC 9(1).
01 ENDO2 PIC 9(1).
01 CURDAY PIC X(50).
01 ABPTR PIC 999.
01 LINE-NUM PIC 9(3) VALUE 1.
01 CHARAMT PIC 9(3) VALUE 1.
01 LARGESTCHARAMT PIC 9(3).
01 DAYNUM PIC 9(3) VALUE 1.
01 ABRESTART PIC 9(1).
01 CURABBR PIC X(50).
01 TMP1 PIC 9(3).
01 TMP2 PIC 9(3).
01 TINDEX PIC 9(3) VALUE 1.
01 ABBRLIST.
05 ABBRITEM PIC X(50) OCCURS 7 TIMES.
PROCEDURE DIVISION.
OPEN INPUT DOW.
PERFORM UNTIL ENDO = 1
READ DOW INTO DOW-LINE
AT END MOVE 1 TO ENDO
NOT AT END PERFORM
IF DOW-LINE = "" THEN
DISPLAY ""
ELSE
MOVE 0 TO ENDO2
MOVE 0 TO CHARAMT
PERFORM UNTIL ENDO2 > 0
MOVE 1 TO ABPTR
MOVE 1 TO DAYNUM
MOVE 0 TO ABRESTART
ADD 1 TO CHARAMT
MOVE 1 TO TINDEX
PERFORM 7 TIMES
MOVE SPACE TO ABBRITEM(TINDEX)
ADD 1 TO TINDEX
END-PERFORM
PERFORM 7 TIMES
UNSTRING DOW-LINE DELIMITED BY SPACE
INTO CURDAY
WITH POINTER ABPTR
END-UNSTRING
MOVE 0 TO TMP1
MOVE 0 TO TMP2
INSPECT CURDAY
TALLYING TMP1 FOR ALL CHARACTERS
INSPECT CURDAY
TALLYING TMP2 FOR ALL SPACE
SUBTRACT TMP2 FROM TMP1
IF TMP1 > LARGESTCHARAMT THEN
MOVE TMP1 TO LARGESTCHARAMT
END-IF
IF CURDAY = "" THEN
MOVE 3 TO ENDO2
END-IF
MOVE CURDAY(1:CHARAMT) TO CURABBR
MOVE 1 TO TINDEX
PERFORM 7 TIMES
IF ABBRITEM(TINDEX) = CURABBR THEN
MOVE 1 TO ABRESTART
END-IF
ADD 1 TO TINDEX
END-PERFORM
MOVE CURABBR TO ABBRITEM(DAYNUM)
ADD 1 TO DAYNUM
END-PERFORM
IF ABRESTART = 0 THEN
MOVE 1 TO ENDO2
END-IF
IF CHARAMT > LARGESTCHARAMT THEN
MOVE 2 TO ENDO2
END-IF
END-PERFORM
DISPLAY "Line " LINE-NUM ": " WITH NO ADVANCING
IF ENDO2 = 3 THEN
DISPLAY "Error: not enough " WITH NO ADVANCING
DISPLAY "days"
ELSE IF ENDO2 = 2 THEN
DISPLAY "Error: identical " WITH NO ADVANCING
DISPLAY "days"
ELSE
DISPLAY CHARAMT ": " WITH NO ADVANCING
MOVE 1 TO TINDEX
PERFORM 7 TIMES
MOVE ABBRITEM(TINDEX) TO CURABBR
MOVE 0 TO TMP1
MOVE 0 TO TMP2
INSPECT CURABBR
TALLYING TMP1 FOR ALL CHARACTERS
INSPECT CURABBR
TALLYING TMP2 FOR TRAILING SPACES
SUBTRACT TMP2 FROM TMP1
DISPLAY CURABBR(1:TMP1) WITH NO ADVANCING
DISPLAY "." WITH NO ADVANCING
IF TINDEX < 7 THEN
DISPLAY SPACE WITH NO ADVANCING
ELSE
DISPLAY X"0a" WITH NO ADVANCING
END-IF
ADD 1 TO TINDEX
END-PERFORM
END-IF
END-IF
END-PERFORM
END-READ
ADD 1 TO LINE-NUM
END-PERFORM.
CLOSE DOW.
STOP RUN.
| #include <stdio.h>
#include <stdlib.h>
#include <string.h>
void process(int lineNum, char buffer[]) {
char days[7][64];
int i = 0, d = 0, j = 0;
while (buffer[i] != 0) {
if (buffer[i] == ' ') {
days[d][j] = '\0';
++d;
j = 0;
} else if (buffer[i] == '\n' || buffer[i] == '\r') {
days[d][j] = '\0';
++d;
break;
} else {
days[d][j] = buffer[i];
++j;
}
if (d >= 7) {
printf("There aren't 7 days in line %d\n", lineNum);
return;
}
++i;
}
if (buffer[i] == '\0') {
days[d][j] = '\0';
++d;
}
if (d < 7) {
printf("There aren't 7 days in line %d\n", lineNum);
return;
} else {
int len = 0;
for (len = 1; len < 64; ++len) {
int d1;
for (d1 = 0; d1 < 7; ++d1) {
int d2;
for (d2 = d1 + 1; d2 < 7; ++d2) {
int unique = 0;
for (i = 0; i < len; ++i) {
if (days[d1][i] != days[d2][i]) {
unique = 1;
break;
}
}
if (!unique) {
goto next_length;
}
}
}
printf("%2d ", len);
for (i = 0; i < 7; ++i) {
printf(" %s", days[i]);
}
printf("\n");
return;
next_length: {}
}
}
printf("Failed to find uniqueness within the bounds.");
}
int main() {
char buffer[1024];
int lineNum = 1, len;
FILE *fp;
fp = fopen("days_of_week.txt", "r");
while (1) {
memset(buffer, 0, sizeof(buffer));
fgets(buffer, sizeof(buffer), fp);
len = strlen(buffer);
if (len == 0 || buffer[len - 1] == '\0') {
break;
}
process(lineNum++, buffer);
}
fclose(fp);
return 0;
}
|
Transform the following COBOL implementation into C#, maintaining the same output and logic. | IDENTIFICATION DIVISION.
PROGRAM-ID. AUTO-ABBREVIATIONS.
ENVIRONMENT DIVISION.
INPUT-OUTPUT SECTION.
FILE-CONTROL.
SELECT DOW ASSIGN TO "days-of-week.txt"
ORGANIZATION IS LINE SEQUENTIAL.
DATA DIVISION.
FILE SECTION.
FD DOW.
01 DOW-FILE PIC X(200).
WORKING-STORAGE SECTION.
01 DOW-LINE PIC X(200).
01 ENDO PIC 9(1).
01 ENDO2 PIC 9(1).
01 CURDAY PIC X(50).
01 ABPTR PIC 999.
01 LINE-NUM PIC 9(3) VALUE 1.
01 CHARAMT PIC 9(3) VALUE 1.
01 LARGESTCHARAMT PIC 9(3).
01 DAYNUM PIC 9(3) VALUE 1.
01 ABRESTART PIC 9(1).
01 CURABBR PIC X(50).
01 TMP1 PIC 9(3).
01 TMP2 PIC 9(3).
01 TINDEX PIC 9(3) VALUE 1.
01 ABBRLIST.
05 ABBRITEM PIC X(50) OCCURS 7 TIMES.
PROCEDURE DIVISION.
OPEN INPUT DOW.
PERFORM UNTIL ENDO = 1
READ DOW INTO DOW-LINE
AT END MOVE 1 TO ENDO
NOT AT END PERFORM
IF DOW-LINE = "" THEN
DISPLAY ""
ELSE
MOVE 0 TO ENDO2
MOVE 0 TO CHARAMT
PERFORM UNTIL ENDO2 > 0
MOVE 1 TO ABPTR
MOVE 1 TO DAYNUM
MOVE 0 TO ABRESTART
ADD 1 TO CHARAMT
MOVE 1 TO TINDEX
PERFORM 7 TIMES
MOVE SPACE TO ABBRITEM(TINDEX)
ADD 1 TO TINDEX
END-PERFORM
PERFORM 7 TIMES
UNSTRING DOW-LINE DELIMITED BY SPACE
INTO CURDAY
WITH POINTER ABPTR
END-UNSTRING
MOVE 0 TO TMP1
MOVE 0 TO TMP2
INSPECT CURDAY
TALLYING TMP1 FOR ALL CHARACTERS
INSPECT CURDAY
TALLYING TMP2 FOR ALL SPACE
SUBTRACT TMP2 FROM TMP1
IF TMP1 > LARGESTCHARAMT THEN
MOVE TMP1 TO LARGESTCHARAMT
END-IF
IF CURDAY = "" THEN
MOVE 3 TO ENDO2
END-IF
MOVE CURDAY(1:CHARAMT) TO CURABBR
MOVE 1 TO TINDEX
PERFORM 7 TIMES
IF ABBRITEM(TINDEX) = CURABBR THEN
MOVE 1 TO ABRESTART
END-IF
ADD 1 TO TINDEX
END-PERFORM
MOVE CURABBR TO ABBRITEM(DAYNUM)
ADD 1 TO DAYNUM
END-PERFORM
IF ABRESTART = 0 THEN
MOVE 1 TO ENDO2
END-IF
IF CHARAMT > LARGESTCHARAMT THEN
MOVE 2 TO ENDO2
END-IF
END-PERFORM
DISPLAY "Line " LINE-NUM ": " WITH NO ADVANCING
IF ENDO2 = 3 THEN
DISPLAY "Error: not enough " WITH NO ADVANCING
DISPLAY "days"
ELSE IF ENDO2 = 2 THEN
DISPLAY "Error: identical " WITH NO ADVANCING
DISPLAY "days"
ELSE
DISPLAY CHARAMT ": " WITH NO ADVANCING
MOVE 1 TO TINDEX
PERFORM 7 TIMES
MOVE ABBRITEM(TINDEX) TO CURABBR
MOVE 0 TO TMP1
MOVE 0 TO TMP2
INSPECT CURABBR
TALLYING TMP1 FOR ALL CHARACTERS
INSPECT CURABBR
TALLYING TMP2 FOR TRAILING SPACES
SUBTRACT TMP2 FROM TMP1
DISPLAY CURABBR(1:TMP1) WITH NO ADVANCING
DISPLAY "." WITH NO ADVANCING
IF TINDEX < 7 THEN
DISPLAY SPACE WITH NO ADVANCING
ELSE
DISPLAY X"0a" WITH NO ADVANCING
END-IF
ADD 1 TO TINDEX
END-PERFORM
END-IF
END-IF
END-PERFORM
END-READ
ADD 1 TO LINE-NUM
END-PERFORM.
CLOSE DOW.
STOP RUN.
| using System;
using System.Collections.Generic;
namespace Abbreviations {
class Program {
static void Main(string[] args) {
string[] lines = System.IO.File.ReadAllLines("days_of_week.txt");
int i = 0;
foreach (string line in lines) {
i++;
if (line.Length > 0) {
var days = line.Split();
if (days.Length != 7) {
throw new Exception("There aren't 7 days in line " + i);
}
Dictionary<string, int> temp = new Dictionary<string, int>();
foreach (string day in days) {
if (temp.ContainsKey(day)) {
Console.WriteLine(" β {0}", line);
continue;
}
temp.Add(day, 1);
}
int len = 1;
while (true) {
temp.Clear();
foreach(string day in days) {
string key;
if (len < day.Length) {
key = day.Substring(0, len);
} else {
key = day;
}
if (temp.ContainsKey(key)) {
break;
}
temp.Add(key, 1);
}
if (temp.Count == 7) {
Console.WriteLine("{0,2:D} {1}", len, line);
break;
}
len++;
}
}
}
}
}
}
|
Port the following code from COBOL to C# with equivalent syntax and logic. | IDENTIFICATION DIVISION.
PROGRAM-ID. AUTO-ABBREVIATIONS.
ENVIRONMENT DIVISION.
INPUT-OUTPUT SECTION.
FILE-CONTROL.
SELECT DOW ASSIGN TO "days-of-week.txt"
ORGANIZATION IS LINE SEQUENTIAL.
DATA DIVISION.
FILE SECTION.
FD DOW.
01 DOW-FILE PIC X(200).
WORKING-STORAGE SECTION.
01 DOW-LINE PIC X(200).
01 ENDO PIC 9(1).
01 ENDO2 PIC 9(1).
01 CURDAY PIC X(50).
01 ABPTR PIC 999.
01 LINE-NUM PIC 9(3) VALUE 1.
01 CHARAMT PIC 9(3) VALUE 1.
01 LARGESTCHARAMT PIC 9(3).
01 DAYNUM PIC 9(3) VALUE 1.
01 ABRESTART PIC 9(1).
01 CURABBR PIC X(50).
01 TMP1 PIC 9(3).
01 TMP2 PIC 9(3).
01 TINDEX PIC 9(3) VALUE 1.
01 ABBRLIST.
05 ABBRITEM PIC X(50) OCCURS 7 TIMES.
PROCEDURE DIVISION.
OPEN INPUT DOW.
PERFORM UNTIL ENDO = 1
READ DOW INTO DOW-LINE
AT END MOVE 1 TO ENDO
NOT AT END PERFORM
IF DOW-LINE = "" THEN
DISPLAY ""
ELSE
MOVE 0 TO ENDO2
MOVE 0 TO CHARAMT
PERFORM UNTIL ENDO2 > 0
MOVE 1 TO ABPTR
MOVE 1 TO DAYNUM
MOVE 0 TO ABRESTART
ADD 1 TO CHARAMT
MOVE 1 TO TINDEX
PERFORM 7 TIMES
MOVE SPACE TO ABBRITEM(TINDEX)
ADD 1 TO TINDEX
END-PERFORM
PERFORM 7 TIMES
UNSTRING DOW-LINE DELIMITED BY SPACE
INTO CURDAY
WITH POINTER ABPTR
END-UNSTRING
MOVE 0 TO TMP1
MOVE 0 TO TMP2
INSPECT CURDAY
TALLYING TMP1 FOR ALL CHARACTERS
INSPECT CURDAY
TALLYING TMP2 FOR ALL SPACE
SUBTRACT TMP2 FROM TMP1
IF TMP1 > LARGESTCHARAMT THEN
MOVE TMP1 TO LARGESTCHARAMT
END-IF
IF CURDAY = "" THEN
MOVE 3 TO ENDO2
END-IF
MOVE CURDAY(1:CHARAMT) TO CURABBR
MOVE 1 TO TINDEX
PERFORM 7 TIMES
IF ABBRITEM(TINDEX) = CURABBR THEN
MOVE 1 TO ABRESTART
END-IF
ADD 1 TO TINDEX
END-PERFORM
MOVE CURABBR TO ABBRITEM(DAYNUM)
ADD 1 TO DAYNUM
END-PERFORM
IF ABRESTART = 0 THEN
MOVE 1 TO ENDO2
END-IF
IF CHARAMT > LARGESTCHARAMT THEN
MOVE 2 TO ENDO2
END-IF
END-PERFORM
DISPLAY "Line " LINE-NUM ": " WITH NO ADVANCING
IF ENDO2 = 3 THEN
DISPLAY "Error: not enough " WITH NO ADVANCING
DISPLAY "days"
ELSE IF ENDO2 = 2 THEN
DISPLAY "Error: identical " WITH NO ADVANCING
DISPLAY "days"
ELSE
DISPLAY CHARAMT ": " WITH NO ADVANCING
MOVE 1 TO TINDEX
PERFORM 7 TIMES
MOVE ABBRITEM(TINDEX) TO CURABBR
MOVE 0 TO TMP1
MOVE 0 TO TMP2
INSPECT CURABBR
TALLYING TMP1 FOR ALL CHARACTERS
INSPECT CURABBR
TALLYING TMP2 FOR TRAILING SPACES
SUBTRACT TMP2 FROM TMP1
DISPLAY CURABBR(1:TMP1) WITH NO ADVANCING
DISPLAY "." WITH NO ADVANCING
IF TINDEX < 7 THEN
DISPLAY SPACE WITH NO ADVANCING
ELSE
DISPLAY X"0a" WITH NO ADVANCING
END-IF
ADD 1 TO TINDEX
END-PERFORM
END-IF
END-IF
END-PERFORM
END-READ
ADD 1 TO LINE-NUM
END-PERFORM.
CLOSE DOW.
STOP RUN.
| using System;
using System.Collections.Generic;
namespace Abbreviations {
class Program {
static void Main(string[] args) {
string[] lines = System.IO.File.ReadAllLines("days_of_week.txt");
int i = 0;
foreach (string line in lines) {
i++;
if (line.Length > 0) {
var days = line.Split();
if (days.Length != 7) {
throw new Exception("There aren't 7 days in line " + i);
}
Dictionary<string, int> temp = new Dictionary<string, int>();
foreach (string day in days) {
if (temp.ContainsKey(day)) {
Console.WriteLine(" β {0}", line);
continue;
}
temp.Add(day, 1);
}
int len = 1;
while (true) {
temp.Clear();
foreach(string day in days) {
string key;
if (len < day.Length) {
key = day.Substring(0, len);
} else {
key = day;
}
if (temp.ContainsKey(key)) {
break;
}
temp.Add(key, 1);
}
if (temp.Count == 7) {
Console.WriteLine("{0,2:D} {1}", len, line);
break;
}
len++;
}
}
}
}
}
}
|
Port the following code from COBOL to C++ with equivalent syntax and logic. | IDENTIFICATION DIVISION.
PROGRAM-ID. AUTO-ABBREVIATIONS.
ENVIRONMENT DIVISION.
INPUT-OUTPUT SECTION.
FILE-CONTROL.
SELECT DOW ASSIGN TO "days-of-week.txt"
ORGANIZATION IS LINE SEQUENTIAL.
DATA DIVISION.
FILE SECTION.
FD DOW.
01 DOW-FILE PIC X(200).
WORKING-STORAGE SECTION.
01 DOW-LINE PIC X(200).
01 ENDO PIC 9(1).
01 ENDO2 PIC 9(1).
01 CURDAY PIC X(50).
01 ABPTR PIC 999.
01 LINE-NUM PIC 9(3) VALUE 1.
01 CHARAMT PIC 9(3) VALUE 1.
01 LARGESTCHARAMT PIC 9(3).
01 DAYNUM PIC 9(3) VALUE 1.
01 ABRESTART PIC 9(1).
01 CURABBR PIC X(50).
01 TMP1 PIC 9(3).
01 TMP2 PIC 9(3).
01 TINDEX PIC 9(3) VALUE 1.
01 ABBRLIST.
05 ABBRITEM PIC X(50) OCCURS 7 TIMES.
PROCEDURE DIVISION.
OPEN INPUT DOW.
PERFORM UNTIL ENDO = 1
READ DOW INTO DOW-LINE
AT END MOVE 1 TO ENDO
NOT AT END PERFORM
IF DOW-LINE = "" THEN
DISPLAY ""
ELSE
MOVE 0 TO ENDO2
MOVE 0 TO CHARAMT
PERFORM UNTIL ENDO2 > 0
MOVE 1 TO ABPTR
MOVE 1 TO DAYNUM
MOVE 0 TO ABRESTART
ADD 1 TO CHARAMT
MOVE 1 TO TINDEX
PERFORM 7 TIMES
MOVE SPACE TO ABBRITEM(TINDEX)
ADD 1 TO TINDEX
END-PERFORM
PERFORM 7 TIMES
UNSTRING DOW-LINE DELIMITED BY SPACE
INTO CURDAY
WITH POINTER ABPTR
END-UNSTRING
MOVE 0 TO TMP1
MOVE 0 TO TMP2
INSPECT CURDAY
TALLYING TMP1 FOR ALL CHARACTERS
INSPECT CURDAY
TALLYING TMP2 FOR ALL SPACE
SUBTRACT TMP2 FROM TMP1
IF TMP1 > LARGESTCHARAMT THEN
MOVE TMP1 TO LARGESTCHARAMT
END-IF
IF CURDAY = "" THEN
MOVE 3 TO ENDO2
END-IF
MOVE CURDAY(1:CHARAMT) TO CURABBR
MOVE 1 TO TINDEX
PERFORM 7 TIMES
IF ABBRITEM(TINDEX) = CURABBR THEN
MOVE 1 TO ABRESTART
END-IF
ADD 1 TO TINDEX
END-PERFORM
MOVE CURABBR TO ABBRITEM(DAYNUM)
ADD 1 TO DAYNUM
END-PERFORM
IF ABRESTART = 0 THEN
MOVE 1 TO ENDO2
END-IF
IF CHARAMT > LARGESTCHARAMT THEN
MOVE 2 TO ENDO2
END-IF
END-PERFORM
DISPLAY "Line " LINE-NUM ": " WITH NO ADVANCING
IF ENDO2 = 3 THEN
DISPLAY "Error: not enough " WITH NO ADVANCING
DISPLAY "days"
ELSE IF ENDO2 = 2 THEN
DISPLAY "Error: identical " WITH NO ADVANCING
DISPLAY "days"
ELSE
DISPLAY CHARAMT ": " WITH NO ADVANCING
MOVE 1 TO TINDEX
PERFORM 7 TIMES
MOVE ABBRITEM(TINDEX) TO CURABBR
MOVE 0 TO TMP1
MOVE 0 TO TMP2
INSPECT CURABBR
TALLYING TMP1 FOR ALL CHARACTERS
INSPECT CURABBR
TALLYING TMP2 FOR TRAILING SPACES
SUBTRACT TMP2 FROM TMP1
DISPLAY CURABBR(1:TMP1) WITH NO ADVANCING
DISPLAY "." WITH NO ADVANCING
IF TINDEX < 7 THEN
DISPLAY SPACE WITH NO ADVANCING
ELSE
DISPLAY X"0a" WITH NO ADVANCING
END-IF
ADD 1 TO TINDEX
END-PERFORM
END-IF
END-IF
END-PERFORM
END-READ
ADD 1 TO LINE-NUM
END-PERFORM.
CLOSE DOW.
STOP RUN.
| #include <iomanip>
#include <iostream>
#include <fstream>
#include <map>
#include <sstream>
#include <string>
#include <vector>
std::vector<std::string> split(const std::string& str, char delimiter) {
std::vector<std::string> tokens;
std::string token;
std::istringstream tokenStream(str);
while (std::getline(tokenStream, token, delimiter)) {
tokens.push_back(token);
}
return tokens;
}
int main() {
using namespace std;
string line;
int i = 0;
ifstream in("days_of_week.txt");
if (in.is_open()) {
while (getline(in, line)) {
i++;
if (line.empty()) {
continue;
}
auto days = split(line, ' ');
if (days.size() != 7) {
throw std::runtime_error("There aren't 7 days in line " + i);
}
map<string, int> temp;
for (auto& day : days) {
if (temp.find(day) != temp.end()) {
cerr << " β " << line << '\n';
continue;
}
temp[day] = 1;
}
int len = 1;
while (true) {
temp.clear();
for (auto& day : days) {
string key = day.substr(0, len);
if (temp.find(key) != temp.end()) {
break;
}
temp[key] = 1;
}
if (temp.size() == 7) {
cout << setw(2) << len << " " << line << '\n';
break;
}
len++;
}
}
}
return 0;
}
|
Convert this COBOL snippet to C++ and keep its semantics consistent. | IDENTIFICATION DIVISION.
PROGRAM-ID. AUTO-ABBREVIATIONS.
ENVIRONMENT DIVISION.
INPUT-OUTPUT SECTION.
FILE-CONTROL.
SELECT DOW ASSIGN TO "days-of-week.txt"
ORGANIZATION IS LINE SEQUENTIAL.
DATA DIVISION.
FILE SECTION.
FD DOW.
01 DOW-FILE PIC X(200).
WORKING-STORAGE SECTION.
01 DOW-LINE PIC X(200).
01 ENDO PIC 9(1).
01 ENDO2 PIC 9(1).
01 CURDAY PIC X(50).
01 ABPTR PIC 999.
01 LINE-NUM PIC 9(3) VALUE 1.
01 CHARAMT PIC 9(3) VALUE 1.
01 LARGESTCHARAMT PIC 9(3).
01 DAYNUM PIC 9(3) VALUE 1.
01 ABRESTART PIC 9(1).
01 CURABBR PIC X(50).
01 TMP1 PIC 9(3).
01 TMP2 PIC 9(3).
01 TINDEX PIC 9(3) VALUE 1.
01 ABBRLIST.
05 ABBRITEM PIC X(50) OCCURS 7 TIMES.
PROCEDURE DIVISION.
OPEN INPUT DOW.
PERFORM UNTIL ENDO = 1
READ DOW INTO DOW-LINE
AT END MOVE 1 TO ENDO
NOT AT END PERFORM
IF DOW-LINE = "" THEN
DISPLAY ""
ELSE
MOVE 0 TO ENDO2
MOVE 0 TO CHARAMT
PERFORM UNTIL ENDO2 > 0
MOVE 1 TO ABPTR
MOVE 1 TO DAYNUM
MOVE 0 TO ABRESTART
ADD 1 TO CHARAMT
MOVE 1 TO TINDEX
PERFORM 7 TIMES
MOVE SPACE TO ABBRITEM(TINDEX)
ADD 1 TO TINDEX
END-PERFORM
PERFORM 7 TIMES
UNSTRING DOW-LINE DELIMITED BY SPACE
INTO CURDAY
WITH POINTER ABPTR
END-UNSTRING
MOVE 0 TO TMP1
MOVE 0 TO TMP2
INSPECT CURDAY
TALLYING TMP1 FOR ALL CHARACTERS
INSPECT CURDAY
TALLYING TMP2 FOR ALL SPACE
SUBTRACT TMP2 FROM TMP1
IF TMP1 > LARGESTCHARAMT THEN
MOVE TMP1 TO LARGESTCHARAMT
END-IF
IF CURDAY = "" THEN
MOVE 3 TO ENDO2
END-IF
MOVE CURDAY(1:CHARAMT) TO CURABBR
MOVE 1 TO TINDEX
PERFORM 7 TIMES
IF ABBRITEM(TINDEX) = CURABBR THEN
MOVE 1 TO ABRESTART
END-IF
ADD 1 TO TINDEX
END-PERFORM
MOVE CURABBR TO ABBRITEM(DAYNUM)
ADD 1 TO DAYNUM
END-PERFORM
IF ABRESTART = 0 THEN
MOVE 1 TO ENDO2
END-IF
IF CHARAMT > LARGESTCHARAMT THEN
MOVE 2 TO ENDO2
END-IF
END-PERFORM
DISPLAY "Line " LINE-NUM ": " WITH NO ADVANCING
IF ENDO2 = 3 THEN
DISPLAY "Error: not enough " WITH NO ADVANCING
DISPLAY "days"
ELSE IF ENDO2 = 2 THEN
DISPLAY "Error: identical " WITH NO ADVANCING
DISPLAY "days"
ELSE
DISPLAY CHARAMT ": " WITH NO ADVANCING
MOVE 1 TO TINDEX
PERFORM 7 TIMES
MOVE ABBRITEM(TINDEX) TO CURABBR
MOVE 0 TO TMP1
MOVE 0 TO TMP2
INSPECT CURABBR
TALLYING TMP1 FOR ALL CHARACTERS
INSPECT CURABBR
TALLYING TMP2 FOR TRAILING SPACES
SUBTRACT TMP2 FROM TMP1
DISPLAY CURABBR(1:TMP1) WITH NO ADVANCING
DISPLAY "." WITH NO ADVANCING
IF TINDEX < 7 THEN
DISPLAY SPACE WITH NO ADVANCING
ELSE
DISPLAY X"0a" WITH NO ADVANCING
END-IF
ADD 1 TO TINDEX
END-PERFORM
END-IF
END-IF
END-PERFORM
END-READ
ADD 1 TO LINE-NUM
END-PERFORM.
CLOSE DOW.
STOP RUN.
| #include <iomanip>
#include <iostream>
#include <fstream>
#include <map>
#include <sstream>
#include <string>
#include <vector>
std::vector<std::string> split(const std::string& str, char delimiter) {
std::vector<std::string> tokens;
std::string token;
std::istringstream tokenStream(str);
while (std::getline(tokenStream, token, delimiter)) {
tokens.push_back(token);
}
return tokens;
}
int main() {
using namespace std;
string line;
int i = 0;
ifstream in("days_of_week.txt");
if (in.is_open()) {
while (getline(in, line)) {
i++;
if (line.empty()) {
continue;
}
auto days = split(line, ' ');
if (days.size() != 7) {
throw std::runtime_error("There aren't 7 days in line " + i);
}
map<string, int> temp;
for (auto& day : days) {
if (temp.find(day) != temp.end()) {
cerr << " β " << line << '\n';
continue;
}
temp[day] = 1;
}
int len = 1;
while (true) {
temp.clear();
for (auto& day : days) {
string key = day.substr(0, len);
if (temp.find(key) != temp.end()) {
break;
}
temp[key] = 1;
}
if (temp.size() == 7) {
cout << setw(2) << len << " " << line << '\n';
break;
}
len++;
}
}
}
return 0;
}
|
Change the programming language of this snippet from COBOL to Java without modifying what it does. | IDENTIFICATION DIVISION.
PROGRAM-ID. AUTO-ABBREVIATIONS.
ENVIRONMENT DIVISION.
INPUT-OUTPUT SECTION.
FILE-CONTROL.
SELECT DOW ASSIGN TO "days-of-week.txt"
ORGANIZATION IS LINE SEQUENTIAL.
DATA DIVISION.
FILE SECTION.
FD DOW.
01 DOW-FILE PIC X(200).
WORKING-STORAGE SECTION.
01 DOW-LINE PIC X(200).
01 ENDO PIC 9(1).
01 ENDO2 PIC 9(1).
01 CURDAY PIC X(50).
01 ABPTR PIC 999.
01 LINE-NUM PIC 9(3) VALUE 1.
01 CHARAMT PIC 9(3) VALUE 1.
01 LARGESTCHARAMT PIC 9(3).
01 DAYNUM PIC 9(3) VALUE 1.
01 ABRESTART PIC 9(1).
01 CURABBR PIC X(50).
01 TMP1 PIC 9(3).
01 TMP2 PIC 9(3).
01 TINDEX PIC 9(3) VALUE 1.
01 ABBRLIST.
05 ABBRITEM PIC X(50) OCCURS 7 TIMES.
PROCEDURE DIVISION.
OPEN INPUT DOW.
PERFORM UNTIL ENDO = 1
READ DOW INTO DOW-LINE
AT END MOVE 1 TO ENDO
NOT AT END PERFORM
IF DOW-LINE = "" THEN
DISPLAY ""
ELSE
MOVE 0 TO ENDO2
MOVE 0 TO CHARAMT
PERFORM UNTIL ENDO2 > 0
MOVE 1 TO ABPTR
MOVE 1 TO DAYNUM
MOVE 0 TO ABRESTART
ADD 1 TO CHARAMT
MOVE 1 TO TINDEX
PERFORM 7 TIMES
MOVE SPACE TO ABBRITEM(TINDEX)
ADD 1 TO TINDEX
END-PERFORM
PERFORM 7 TIMES
UNSTRING DOW-LINE DELIMITED BY SPACE
INTO CURDAY
WITH POINTER ABPTR
END-UNSTRING
MOVE 0 TO TMP1
MOVE 0 TO TMP2
INSPECT CURDAY
TALLYING TMP1 FOR ALL CHARACTERS
INSPECT CURDAY
TALLYING TMP2 FOR ALL SPACE
SUBTRACT TMP2 FROM TMP1
IF TMP1 > LARGESTCHARAMT THEN
MOVE TMP1 TO LARGESTCHARAMT
END-IF
IF CURDAY = "" THEN
MOVE 3 TO ENDO2
END-IF
MOVE CURDAY(1:CHARAMT) TO CURABBR
MOVE 1 TO TINDEX
PERFORM 7 TIMES
IF ABBRITEM(TINDEX) = CURABBR THEN
MOVE 1 TO ABRESTART
END-IF
ADD 1 TO TINDEX
END-PERFORM
MOVE CURABBR TO ABBRITEM(DAYNUM)
ADD 1 TO DAYNUM
END-PERFORM
IF ABRESTART = 0 THEN
MOVE 1 TO ENDO2
END-IF
IF CHARAMT > LARGESTCHARAMT THEN
MOVE 2 TO ENDO2
END-IF
END-PERFORM
DISPLAY "Line " LINE-NUM ": " WITH NO ADVANCING
IF ENDO2 = 3 THEN
DISPLAY "Error: not enough " WITH NO ADVANCING
DISPLAY "days"
ELSE IF ENDO2 = 2 THEN
DISPLAY "Error: identical " WITH NO ADVANCING
DISPLAY "days"
ELSE
DISPLAY CHARAMT ": " WITH NO ADVANCING
MOVE 1 TO TINDEX
PERFORM 7 TIMES
MOVE ABBRITEM(TINDEX) TO CURABBR
MOVE 0 TO TMP1
MOVE 0 TO TMP2
INSPECT CURABBR
TALLYING TMP1 FOR ALL CHARACTERS
INSPECT CURABBR
TALLYING TMP2 FOR TRAILING SPACES
SUBTRACT TMP2 FROM TMP1
DISPLAY CURABBR(1:TMP1) WITH NO ADVANCING
DISPLAY "." WITH NO ADVANCING
IF TINDEX < 7 THEN
DISPLAY SPACE WITH NO ADVANCING
ELSE
DISPLAY X"0a" WITH NO ADVANCING
END-IF
ADD 1 TO TINDEX
END-PERFORM
END-IF
END-IF
END-PERFORM
END-READ
ADD 1 TO LINE-NUM
END-PERFORM.
CLOSE DOW.
STOP RUN.
| import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class Abbreviations {
public static void main(String[] args) throws IOException {
Path path = Paths.get("days_of_week.txt");
List<String> readAllLines = Files.readAllLines(path);
for (int i = 0; i < readAllLines.size(); i++) {
String line = readAllLines.get(i);
if (line.length() == 0) continue;
String[] days = line.split(" ");
if (days.length != 7) throw new RuntimeException("There aren't 7 days on line " + (i + 1));
Map<String, Integer> temp = new HashMap<>();
for (String day : days) {
Integer count = temp.getOrDefault(day, 0);
temp.put(day, count + 1);
}
if (temp.size() < 7) {
System.out.print(" β ");
System.out.println(line);
continue;
}
int len = 1;
while (true) {
temp.clear();
for (String day : days) {
String sd;
if (len >= day.length()) {
sd = day;
} else {
sd = day.substring(0, len);
}
Integer count = temp.getOrDefault(sd, 0);
temp.put(sd, count + 1);
}
if (temp.size() == 7) {
System.out.printf("%2d %s\n", len, line);
break;
}
len++;
}
}
}
}
|
Rewrite this program in Java while keeping its functionality equivalent to the COBOL version. | IDENTIFICATION DIVISION.
PROGRAM-ID. AUTO-ABBREVIATIONS.
ENVIRONMENT DIVISION.
INPUT-OUTPUT SECTION.
FILE-CONTROL.
SELECT DOW ASSIGN TO "days-of-week.txt"
ORGANIZATION IS LINE SEQUENTIAL.
DATA DIVISION.
FILE SECTION.
FD DOW.
01 DOW-FILE PIC X(200).
WORKING-STORAGE SECTION.
01 DOW-LINE PIC X(200).
01 ENDO PIC 9(1).
01 ENDO2 PIC 9(1).
01 CURDAY PIC X(50).
01 ABPTR PIC 999.
01 LINE-NUM PIC 9(3) VALUE 1.
01 CHARAMT PIC 9(3) VALUE 1.
01 LARGESTCHARAMT PIC 9(3).
01 DAYNUM PIC 9(3) VALUE 1.
01 ABRESTART PIC 9(1).
01 CURABBR PIC X(50).
01 TMP1 PIC 9(3).
01 TMP2 PIC 9(3).
01 TINDEX PIC 9(3) VALUE 1.
01 ABBRLIST.
05 ABBRITEM PIC X(50) OCCURS 7 TIMES.
PROCEDURE DIVISION.
OPEN INPUT DOW.
PERFORM UNTIL ENDO = 1
READ DOW INTO DOW-LINE
AT END MOVE 1 TO ENDO
NOT AT END PERFORM
IF DOW-LINE = "" THEN
DISPLAY ""
ELSE
MOVE 0 TO ENDO2
MOVE 0 TO CHARAMT
PERFORM UNTIL ENDO2 > 0
MOVE 1 TO ABPTR
MOVE 1 TO DAYNUM
MOVE 0 TO ABRESTART
ADD 1 TO CHARAMT
MOVE 1 TO TINDEX
PERFORM 7 TIMES
MOVE SPACE TO ABBRITEM(TINDEX)
ADD 1 TO TINDEX
END-PERFORM
PERFORM 7 TIMES
UNSTRING DOW-LINE DELIMITED BY SPACE
INTO CURDAY
WITH POINTER ABPTR
END-UNSTRING
MOVE 0 TO TMP1
MOVE 0 TO TMP2
INSPECT CURDAY
TALLYING TMP1 FOR ALL CHARACTERS
INSPECT CURDAY
TALLYING TMP2 FOR ALL SPACE
SUBTRACT TMP2 FROM TMP1
IF TMP1 > LARGESTCHARAMT THEN
MOVE TMP1 TO LARGESTCHARAMT
END-IF
IF CURDAY = "" THEN
MOVE 3 TO ENDO2
END-IF
MOVE CURDAY(1:CHARAMT) TO CURABBR
MOVE 1 TO TINDEX
PERFORM 7 TIMES
IF ABBRITEM(TINDEX) = CURABBR THEN
MOVE 1 TO ABRESTART
END-IF
ADD 1 TO TINDEX
END-PERFORM
MOVE CURABBR TO ABBRITEM(DAYNUM)
ADD 1 TO DAYNUM
END-PERFORM
IF ABRESTART = 0 THEN
MOVE 1 TO ENDO2
END-IF
IF CHARAMT > LARGESTCHARAMT THEN
MOVE 2 TO ENDO2
END-IF
END-PERFORM
DISPLAY "Line " LINE-NUM ": " WITH NO ADVANCING
IF ENDO2 = 3 THEN
DISPLAY "Error: not enough " WITH NO ADVANCING
DISPLAY "days"
ELSE IF ENDO2 = 2 THEN
DISPLAY "Error: identical " WITH NO ADVANCING
DISPLAY "days"
ELSE
DISPLAY CHARAMT ": " WITH NO ADVANCING
MOVE 1 TO TINDEX
PERFORM 7 TIMES
MOVE ABBRITEM(TINDEX) TO CURABBR
MOVE 0 TO TMP1
MOVE 0 TO TMP2
INSPECT CURABBR
TALLYING TMP1 FOR ALL CHARACTERS
INSPECT CURABBR
TALLYING TMP2 FOR TRAILING SPACES
SUBTRACT TMP2 FROM TMP1
DISPLAY CURABBR(1:TMP1) WITH NO ADVANCING
DISPLAY "." WITH NO ADVANCING
IF TINDEX < 7 THEN
DISPLAY SPACE WITH NO ADVANCING
ELSE
DISPLAY X"0a" WITH NO ADVANCING
END-IF
ADD 1 TO TINDEX
END-PERFORM
END-IF
END-IF
END-PERFORM
END-READ
ADD 1 TO LINE-NUM
END-PERFORM.
CLOSE DOW.
STOP RUN.
| import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class Abbreviations {
public static void main(String[] args) throws IOException {
Path path = Paths.get("days_of_week.txt");
List<String> readAllLines = Files.readAllLines(path);
for (int i = 0; i < readAllLines.size(); i++) {
String line = readAllLines.get(i);
if (line.length() == 0) continue;
String[] days = line.split(" ");
if (days.length != 7) throw new RuntimeException("There aren't 7 days on line " + (i + 1));
Map<String, Integer> temp = new HashMap<>();
for (String day : days) {
Integer count = temp.getOrDefault(day, 0);
temp.put(day, count + 1);
}
if (temp.size() < 7) {
System.out.print(" β ");
System.out.println(line);
continue;
}
int len = 1;
while (true) {
temp.clear();
for (String day : days) {
String sd;
if (len >= day.length()) {
sd = day;
} else {
sd = day.substring(0, len);
}
Integer count = temp.getOrDefault(sd, 0);
temp.put(sd, count + 1);
}
if (temp.size() == 7) {
System.out.printf("%2d %s\n", len, line);
break;
}
len++;
}
}
}
}
|
Generate a Python translation of this COBOL snippet without changing its computational steps. | IDENTIFICATION DIVISION.
PROGRAM-ID. AUTO-ABBREVIATIONS.
ENVIRONMENT DIVISION.
INPUT-OUTPUT SECTION.
FILE-CONTROL.
SELECT DOW ASSIGN TO "days-of-week.txt"
ORGANIZATION IS LINE SEQUENTIAL.
DATA DIVISION.
FILE SECTION.
FD DOW.
01 DOW-FILE PIC X(200).
WORKING-STORAGE SECTION.
01 DOW-LINE PIC X(200).
01 ENDO PIC 9(1).
01 ENDO2 PIC 9(1).
01 CURDAY PIC X(50).
01 ABPTR PIC 999.
01 LINE-NUM PIC 9(3) VALUE 1.
01 CHARAMT PIC 9(3) VALUE 1.
01 LARGESTCHARAMT PIC 9(3).
01 DAYNUM PIC 9(3) VALUE 1.
01 ABRESTART PIC 9(1).
01 CURABBR PIC X(50).
01 TMP1 PIC 9(3).
01 TMP2 PIC 9(3).
01 TINDEX PIC 9(3) VALUE 1.
01 ABBRLIST.
05 ABBRITEM PIC X(50) OCCURS 7 TIMES.
PROCEDURE DIVISION.
OPEN INPUT DOW.
PERFORM UNTIL ENDO = 1
READ DOW INTO DOW-LINE
AT END MOVE 1 TO ENDO
NOT AT END PERFORM
IF DOW-LINE = "" THEN
DISPLAY ""
ELSE
MOVE 0 TO ENDO2
MOVE 0 TO CHARAMT
PERFORM UNTIL ENDO2 > 0
MOVE 1 TO ABPTR
MOVE 1 TO DAYNUM
MOVE 0 TO ABRESTART
ADD 1 TO CHARAMT
MOVE 1 TO TINDEX
PERFORM 7 TIMES
MOVE SPACE TO ABBRITEM(TINDEX)
ADD 1 TO TINDEX
END-PERFORM
PERFORM 7 TIMES
UNSTRING DOW-LINE DELIMITED BY SPACE
INTO CURDAY
WITH POINTER ABPTR
END-UNSTRING
MOVE 0 TO TMP1
MOVE 0 TO TMP2
INSPECT CURDAY
TALLYING TMP1 FOR ALL CHARACTERS
INSPECT CURDAY
TALLYING TMP2 FOR ALL SPACE
SUBTRACT TMP2 FROM TMP1
IF TMP1 > LARGESTCHARAMT THEN
MOVE TMP1 TO LARGESTCHARAMT
END-IF
IF CURDAY = "" THEN
MOVE 3 TO ENDO2
END-IF
MOVE CURDAY(1:CHARAMT) TO CURABBR
MOVE 1 TO TINDEX
PERFORM 7 TIMES
IF ABBRITEM(TINDEX) = CURABBR THEN
MOVE 1 TO ABRESTART
END-IF
ADD 1 TO TINDEX
END-PERFORM
MOVE CURABBR TO ABBRITEM(DAYNUM)
ADD 1 TO DAYNUM
END-PERFORM
IF ABRESTART = 0 THEN
MOVE 1 TO ENDO2
END-IF
IF CHARAMT > LARGESTCHARAMT THEN
MOVE 2 TO ENDO2
END-IF
END-PERFORM
DISPLAY "Line " LINE-NUM ": " WITH NO ADVANCING
IF ENDO2 = 3 THEN
DISPLAY "Error: not enough " WITH NO ADVANCING
DISPLAY "days"
ELSE IF ENDO2 = 2 THEN
DISPLAY "Error: identical " WITH NO ADVANCING
DISPLAY "days"
ELSE
DISPLAY CHARAMT ": " WITH NO ADVANCING
MOVE 1 TO TINDEX
PERFORM 7 TIMES
MOVE ABBRITEM(TINDEX) TO CURABBR
MOVE 0 TO TMP1
MOVE 0 TO TMP2
INSPECT CURABBR
TALLYING TMP1 FOR ALL CHARACTERS
INSPECT CURABBR
TALLYING TMP2 FOR TRAILING SPACES
SUBTRACT TMP2 FROM TMP1
DISPLAY CURABBR(1:TMP1) WITH NO ADVANCING
DISPLAY "." WITH NO ADVANCING
IF TINDEX < 7 THEN
DISPLAY SPACE WITH NO ADVANCING
ELSE
DISPLAY X"0a" WITH NO ADVANCING
END-IF
ADD 1 TO TINDEX
END-PERFORM
END-IF
END-IF
END-PERFORM
END-READ
ADD 1 TO LINE-NUM
END-PERFORM.
CLOSE DOW.
STOP RUN.
| def shortest_abbreviation_length(line, list_size):
words = line.split()
word_count = len(words)
if word_count != list_size:
raise ValueError(f'Not enough entries, expected {list_size} found {word_count}')
abbreviation_length = 1
abbreviations = set()
while(True):
abbreviations = {word[:abbreviation_length] for word in words}
if len(abbreviations) == list_size:
return abbreviation_length
abbreviation_length += 1
abbreviations.clear()
def automatic_abbreviations(filename, words_per_line):
with open(filename) as file:
for line in file:
line = line.rstrip()
if len(line) > 0:
length = shortest_abbreviation_length(line, words_per_line)
print(f'{length:2} {line}')
else:
print()
automatic_abbreviations('daysOfWeek.txt', 7)
|
Maintain the same structure and functionality when rewriting this code in Python. | IDENTIFICATION DIVISION.
PROGRAM-ID. AUTO-ABBREVIATIONS.
ENVIRONMENT DIVISION.
INPUT-OUTPUT SECTION.
FILE-CONTROL.
SELECT DOW ASSIGN TO "days-of-week.txt"
ORGANIZATION IS LINE SEQUENTIAL.
DATA DIVISION.
FILE SECTION.
FD DOW.
01 DOW-FILE PIC X(200).
WORKING-STORAGE SECTION.
01 DOW-LINE PIC X(200).
01 ENDO PIC 9(1).
01 ENDO2 PIC 9(1).
01 CURDAY PIC X(50).
01 ABPTR PIC 999.
01 LINE-NUM PIC 9(3) VALUE 1.
01 CHARAMT PIC 9(3) VALUE 1.
01 LARGESTCHARAMT PIC 9(3).
01 DAYNUM PIC 9(3) VALUE 1.
01 ABRESTART PIC 9(1).
01 CURABBR PIC X(50).
01 TMP1 PIC 9(3).
01 TMP2 PIC 9(3).
01 TINDEX PIC 9(3) VALUE 1.
01 ABBRLIST.
05 ABBRITEM PIC X(50) OCCURS 7 TIMES.
PROCEDURE DIVISION.
OPEN INPUT DOW.
PERFORM UNTIL ENDO = 1
READ DOW INTO DOW-LINE
AT END MOVE 1 TO ENDO
NOT AT END PERFORM
IF DOW-LINE = "" THEN
DISPLAY ""
ELSE
MOVE 0 TO ENDO2
MOVE 0 TO CHARAMT
PERFORM UNTIL ENDO2 > 0
MOVE 1 TO ABPTR
MOVE 1 TO DAYNUM
MOVE 0 TO ABRESTART
ADD 1 TO CHARAMT
MOVE 1 TO TINDEX
PERFORM 7 TIMES
MOVE SPACE TO ABBRITEM(TINDEX)
ADD 1 TO TINDEX
END-PERFORM
PERFORM 7 TIMES
UNSTRING DOW-LINE DELIMITED BY SPACE
INTO CURDAY
WITH POINTER ABPTR
END-UNSTRING
MOVE 0 TO TMP1
MOVE 0 TO TMP2
INSPECT CURDAY
TALLYING TMP1 FOR ALL CHARACTERS
INSPECT CURDAY
TALLYING TMP2 FOR ALL SPACE
SUBTRACT TMP2 FROM TMP1
IF TMP1 > LARGESTCHARAMT THEN
MOVE TMP1 TO LARGESTCHARAMT
END-IF
IF CURDAY = "" THEN
MOVE 3 TO ENDO2
END-IF
MOVE CURDAY(1:CHARAMT) TO CURABBR
MOVE 1 TO TINDEX
PERFORM 7 TIMES
IF ABBRITEM(TINDEX) = CURABBR THEN
MOVE 1 TO ABRESTART
END-IF
ADD 1 TO TINDEX
END-PERFORM
MOVE CURABBR TO ABBRITEM(DAYNUM)
ADD 1 TO DAYNUM
END-PERFORM
IF ABRESTART = 0 THEN
MOVE 1 TO ENDO2
END-IF
IF CHARAMT > LARGESTCHARAMT THEN
MOVE 2 TO ENDO2
END-IF
END-PERFORM
DISPLAY "Line " LINE-NUM ": " WITH NO ADVANCING
IF ENDO2 = 3 THEN
DISPLAY "Error: not enough " WITH NO ADVANCING
DISPLAY "days"
ELSE IF ENDO2 = 2 THEN
DISPLAY "Error: identical " WITH NO ADVANCING
DISPLAY "days"
ELSE
DISPLAY CHARAMT ": " WITH NO ADVANCING
MOVE 1 TO TINDEX
PERFORM 7 TIMES
MOVE ABBRITEM(TINDEX) TO CURABBR
MOVE 0 TO TMP1
MOVE 0 TO TMP2
INSPECT CURABBR
TALLYING TMP1 FOR ALL CHARACTERS
INSPECT CURABBR
TALLYING TMP2 FOR TRAILING SPACES
SUBTRACT TMP2 FROM TMP1
DISPLAY CURABBR(1:TMP1) WITH NO ADVANCING
DISPLAY "." WITH NO ADVANCING
IF TINDEX < 7 THEN
DISPLAY SPACE WITH NO ADVANCING
ELSE
DISPLAY X"0a" WITH NO ADVANCING
END-IF
ADD 1 TO TINDEX
END-PERFORM
END-IF
END-IF
END-PERFORM
END-READ
ADD 1 TO LINE-NUM
END-PERFORM.
CLOSE DOW.
STOP RUN.
| def shortest_abbreviation_length(line, list_size):
words = line.split()
word_count = len(words)
if word_count != list_size:
raise ValueError(f'Not enough entries, expected {list_size} found {word_count}')
abbreviation_length = 1
abbreviations = set()
while(True):
abbreviations = {word[:abbreviation_length] for word in words}
if len(abbreviations) == list_size:
return abbreviation_length
abbreviation_length += 1
abbreviations.clear()
def automatic_abbreviations(filename, words_per_line):
with open(filename) as file:
for line in file:
line = line.rstrip()
if len(line) > 0:
length = shortest_abbreviation_length(line, words_per_line)
print(f'{length:2} {line}')
else:
print()
automatic_abbreviations('daysOfWeek.txt', 7)
|
Translate this program into VB but keep the logic exactly as in COBOL. | IDENTIFICATION DIVISION.
PROGRAM-ID. AUTO-ABBREVIATIONS.
ENVIRONMENT DIVISION.
INPUT-OUTPUT SECTION.
FILE-CONTROL.
SELECT DOW ASSIGN TO "days-of-week.txt"
ORGANIZATION IS LINE SEQUENTIAL.
DATA DIVISION.
FILE SECTION.
FD DOW.
01 DOW-FILE PIC X(200).
WORKING-STORAGE SECTION.
01 DOW-LINE PIC X(200).
01 ENDO PIC 9(1).
01 ENDO2 PIC 9(1).
01 CURDAY PIC X(50).
01 ABPTR PIC 999.
01 LINE-NUM PIC 9(3) VALUE 1.
01 CHARAMT PIC 9(3) VALUE 1.
01 LARGESTCHARAMT PIC 9(3).
01 DAYNUM PIC 9(3) VALUE 1.
01 ABRESTART PIC 9(1).
01 CURABBR PIC X(50).
01 TMP1 PIC 9(3).
01 TMP2 PIC 9(3).
01 TINDEX PIC 9(3) VALUE 1.
01 ABBRLIST.
05 ABBRITEM PIC X(50) OCCURS 7 TIMES.
PROCEDURE DIVISION.
OPEN INPUT DOW.
PERFORM UNTIL ENDO = 1
READ DOW INTO DOW-LINE
AT END MOVE 1 TO ENDO
NOT AT END PERFORM
IF DOW-LINE = "" THEN
DISPLAY ""
ELSE
MOVE 0 TO ENDO2
MOVE 0 TO CHARAMT
PERFORM UNTIL ENDO2 > 0
MOVE 1 TO ABPTR
MOVE 1 TO DAYNUM
MOVE 0 TO ABRESTART
ADD 1 TO CHARAMT
MOVE 1 TO TINDEX
PERFORM 7 TIMES
MOVE SPACE TO ABBRITEM(TINDEX)
ADD 1 TO TINDEX
END-PERFORM
PERFORM 7 TIMES
UNSTRING DOW-LINE DELIMITED BY SPACE
INTO CURDAY
WITH POINTER ABPTR
END-UNSTRING
MOVE 0 TO TMP1
MOVE 0 TO TMP2
INSPECT CURDAY
TALLYING TMP1 FOR ALL CHARACTERS
INSPECT CURDAY
TALLYING TMP2 FOR ALL SPACE
SUBTRACT TMP2 FROM TMP1
IF TMP1 > LARGESTCHARAMT THEN
MOVE TMP1 TO LARGESTCHARAMT
END-IF
IF CURDAY = "" THEN
MOVE 3 TO ENDO2
END-IF
MOVE CURDAY(1:CHARAMT) TO CURABBR
MOVE 1 TO TINDEX
PERFORM 7 TIMES
IF ABBRITEM(TINDEX) = CURABBR THEN
MOVE 1 TO ABRESTART
END-IF
ADD 1 TO TINDEX
END-PERFORM
MOVE CURABBR TO ABBRITEM(DAYNUM)
ADD 1 TO DAYNUM
END-PERFORM
IF ABRESTART = 0 THEN
MOVE 1 TO ENDO2
END-IF
IF CHARAMT > LARGESTCHARAMT THEN
MOVE 2 TO ENDO2
END-IF
END-PERFORM
DISPLAY "Line " LINE-NUM ": " WITH NO ADVANCING
IF ENDO2 = 3 THEN
DISPLAY "Error: not enough " WITH NO ADVANCING
DISPLAY "days"
ELSE IF ENDO2 = 2 THEN
DISPLAY "Error: identical " WITH NO ADVANCING
DISPLAY "days"
ELSE
DISPLAY CHARAMT ": " WITH NO ADVANCING
MOVE 1 TO TINDEX
PERFORM 7 TIMES
MOVE ABBRITEM(TINDEX) TO CURABBR
MOVE 0 TO TMP1
MOVE 0 TO TMP2
INSPECT CURABBR
TALLYING TMP1 FOR ALL CHARACTERS
INSPECT CURABBR
TALLYING TMP2 FOR TRAILING SPACES
SUBTRACT TMP2 FROM TMP1
DISPLAY CURABBR(1:TMP1) WITH NO ADVANCING
DISPLAY "." WITH NO ADVANCING
IF TINDEX < 7 THEN
DISPLAY SPACE WITH NO ADVANCING
ELSE
DISPLAY X"0a" WITH NO ADVANCING
END-IF
ADD 1 TO TINDEX
END-PERFORM
END-IF
END-IF
END-PERFORM
END-READ
ADD 1 TO LINE-NUM
END-PERFORM.
CLOSE DOW.
STOP RUN.
| Function MinimalLenght(strLine As String) As Integer
Dim myVar As Variant, I As Integer, Flag As Boolean, myColl As Collection, Count As Integer
myVar = Split(strLine, " ")
Count = 0
Do
Set myColl = New Collection
Count = Count + 1
On Error Resume Next
Do
myColl.Add Left$(myVar(I), Count), Left$(myVar(I), Count)
I = I + 1
Loop While Err.Number = 0 And I <= UBound(myVar)
Flag = Err.Number = 0
On Error GoTo 0
I = 0
Set myColl = Nothing
Loop While Not Flag
MinimalLenght = Count
End Function
|
Write a version of this COBOL function in VB with identical behavior. | IDENTIFICATION DIVISION.
PROGRAM-ID. AUTO-ABBREVIATIONS.
ENVIRONMENT DIVISION.
INPUT-OUTPUT SECTION.
FILE-CONTROL.
SELECT DOW ASSIGN TO "days-of-week.txt"
ORGANIZATION IS LINE SEQUENTIAL.
DATA DIVISION.
FILE SECTION.
FD DOW.
01 DOW-FILE PIC X(200).
WORKING-STORAGE SECTION.
01 DOW-LINE PIC X(200).
01 ENDO PIC 9(1).
01 ENDO2 PIC 9(1).
01 CURDAY PIC X(50).
01 ABPTR PIC 999.
01 LINE-NUM PIC 9(3) VALUE 1.
01 CHARAMT PIC 9(3) VALUE 1.
01 LARGESTCHARAMT PIC 9(3).
01 DAYNUM PIC 9(3) VALUE 1.
01 ABRESTART PIC 9(1).
01 CURABBR PIC X(50).
01 TMP1 PIC 9(3).
01 TMP2 PIC 9(3).
01 TINDEX PIC 9(3) VALUE 1.
01 ABBRLIST.
05 ABBRITEM PIC X(50) OCCURS 7 TIMES.
PROCEDURE DIVISION.
OPEN INPUT DOW.
PERFORM UNTIL ENDO = 1
READ DOW INTO DOW-LINE
AT END MOVE 1 TO ENDO
NOT AT END PERFORM
IF DOW-LINE = "" THEN
DISPLAY ""
ELSE
MOVE 0 TO ENDO2
MOVE 0 TO CHARAMT
PERFORM UNTIL ENDO2 > 0
MOVE 1 TO ABPTR
MOVE 1 TO DAYNUM
MOVE 0 TO ABRESTART
ADD 1 TO CHARAMT
MOVE 1 TO TINDEX
PERFORM 7 TIMES
MOVE SPACE TO ABBRITEM(TINDEX)
ADD 1 TO TINDEX
END-PERFORM
PERFORM 7 TIMES
UNSTRING DOW-LINE DELIMITED BY SPACE
INTO CURDAY
WITH POINTER ABPTR
END-UNSTRING
MOVE 0 TO TMP1
MOVE 0 TO TMP2
INSPECT CURDAY
TALLYING TMP1 FOR ALL CHARACTERS
INSPECT CURDAY
TALLYING TMP2 FOR ALL SPACE
SUBTRACT TMP2 FROM TMP1
IF TMP1 > LARGESTCHARAMT THEN
MOVE TMP1 TO LARGESTCHARAMT
END-IF
IF CURDAY = "" THEN
MOVE 3 TO ENDO2
END-IF
MOVE CURDAY(1:CHARAMT) TO CURABBR
MOVE 1 TO TINDEX
PERFORM 7 TIMES
IF ABBRITEM(TINDEX) = CURABBR THEN
MOVE 1 TO ABRESTART
END-IF
ADD 1 TO TINDEX
END-PERFORM
MOVE CURABBR TO ABBRITEM(DAYNUM)
ADD 1 TO DAYNUM
END-PERFORM
IF ABRESTART = 0 THEN
MOVE 1 TO ENDO2
END-IF
IF CHARAMT > LARGESTCHARAMT THEN
MOVE 2 TO ENDO2
END-IF
END-PERFORM
DISPLAY "Line " LINE-NUM ": " WITH NO ADVANCING
IF ENDO2 = 3 THEN
DISPLAY "Error: not enough " WITH NO ADVANCING
DISPLAY "days"
ELSE IF ENDO2 = 2 THEN
DISPLAY "Error: identical " WITH NO ADVANCING
DISPLAY "days"
ELSE
DISPLAY CHARAMT ": " WITH NO ADVANCING
MOVE 1 TO TINDEX
PERFORM 7 TIMES
MOVE ABBRITEM(TINDEX) TO CURABBR
MOVE 0 TO TMP1
MOVE 0 TO TMP2
INSPECT CURABBR
TALLYING TMP1 FOR ALL CHARACTERS
INSPECT CURABBR
TALLYING TMP2 FOR TRAILING SPACES
SUBTRACT TMP2 FROM TMP1
DISPLAY CURABBR(1:TMP1) WITH NO ADVANCING
DISPLAY "." WITH NO ADVANCING
IF TINDEX < 7 THEN
DISPLAY SPACE WITH NO ADVANCING
ELSE
DISPLAY X"0a" WITH NO ADVANCING
END-IF
ADD 1 TO TINDEX
END-PERFORM
END-IF
END-IF
END-PERFORM
END-READ
ADD 1 TO LINE-NUM
END-PERFORM.
CLOSE DOW.
STOP RUN.
| Function MinimalLenght(strLine As String) As Integer
Dim myVar As Variant, I As Integer, Flag As Boolean, myColl As Collection, Count As Integer
myVar = Split(strLine, " ")
Count = 0
Do
Set myColl = New Collection
Count = Count + 1
On Error Resume Next
Do
myColl.Add Left$(myVar(I), Count), Left$(myVar(I), Count)
I = I + 1
Loop While Err.Number = 0 And I <= UBound(myVar)
Flag = Err.Number = 0
On Error GoTo 0
I = 0
Set myColl = Nothing
Loop While Not Flag
MinimalLenght = Count
End Function
|
Can you help me rewrite this code in Go instead of COBOL, keeping it the same logically? | IDENTIFICATION DIVISION.
PROGRAM-ID. AUTO-ABBREVIATIONS.
ENVIRONMENT DIVISION.
INPUT-OUTPUT SECTION.
FILE-CONTROL.
SELECT DOW ASSIGN TO "days-of-week.txt"
ORGANIZATION IS LINE SEQUENTIAL.
DATA DIVISION.
FILE SECTION.
FD DOW.
01 DOW-FILE PIC X(200).
WORKING-STORAGE SECTION.
01 DOW-LINE PIC X(200).
01 ENDO PIC 9(1).
01 ENDO2 PIC 9(1).
01 CURDAY PIC X(50).
01 ABPTR PIC 999.
01 LINE-NUM PIC 9(3) VALUE 1.
01 CHARAMT PIC 9(3) VALUE 1.
01 LARGESTCHARAMT PIC 9(3).
01 DAYNUM PIC 9(3) VALUE 1.
01 ABRESTART PIC 9(1).
01 CURABBR PIC X(50).
01 TMP1 PIC 9(3).
01 TMP2 PIC 9(3).
01 TINDEX PIC 9(3) VALUE 1.
01 ABBRLIST.
05 ABBRITEM PIC X(50) OCCURS 7 TIMES.
PROCEDURE DIVISION.
OPEN INPUT DOW.
PERFORM UNTIL ENDO = 1
READ DOW INTO DOW-LINE
AT END MOVE 1 TO ENDO
NOT AT END PERFORM
IF DOW-LINE = "" THEN
DISPLAY ""
ELSE
MOVE 0 TO ENDO2
MOVE 0 TO CHARAMT
PERFORM UNTIL ENDO2 > 0
MOVE 1 TO ABPTR
MOVE 1 TO DAYNUM
MOVE 0 TO ABRESTART
ADD 1 TO CHARAMT
MOVE 1 TO TINDEX
PERFORM 7 TIMES
MOVE SPACE TO ABBRITEM(TINDEX)
ADD 1 TO TINDEX
END-PERFORM
PERFORM 7 TIMES
UNSTRING DOW-LINE DELIMITED BY SPACE
INTO CURDAY
WITH POINTER ABPTR
END-UNSTRING
MOVE 0 TO TMP1
MOVE 0 TO TMP2
INSPECT CURDAY
TALLYING TMP1 FOR ALL CHARACTERS
INSPECT CURDAY
TALLYING TMP2 FOR ALL SPACE
SUBTRACT TMP2 FROM TMP1
IF TMP1 > LARGESTCHARAMT THEN
MOVE TMP1 TO LARGESTCHARAMT
END-IF
IF CURDAY = "" THEN
MOVE 3 TO ENDO2
END-IF
MOVE CURDAY(1:CHARAMT) TO CURABBR
MOVE 1 TO TINDEX
PERFORM 7 TIMES
IF ABBRITEM(TINDEX) = CURABBR THEN
MOVE 1 TO ABRESTART
END-IF
ADD 1 TO TINDEX
END-PERFORM
MOVE CURABBR TO ABBRITEM(DAYNUM)
ADD 1 TO DAYNUM
END-PERFORM
IF ABRESTART = 0 THEN
MOVE 1 TO ENDO2
END-IF
IF CHARAMT > LARGESTCHARAMT THEN
MOVE 2 TO ENDO2
END-IF
END-PERFORM
DISPLAY "Line " LINE-NUM ": " WITH NO ADVANCING
IF ENDO2 = 3 THEN
DISPLAY "Error: not enough " WITH NO ADVANCING
DISPLAY "days"
ELSE IF ENDO2 = 2 THEN
DISPLAY "Error: identical " WITH NO ADVANCING
DISPLAY "days"
ELSE
DISPLAY CHARAMT ": " WITH NO ADVANCING
MOVE 1 TO TINDEX
PERFORM 7 TIMES
MOVE ABBRITEM(TINDEX) TO CURABBR
MOVE 0 TO TMP1
MOVE 0 TO TMP2
INSPECT CURABBR
TALLYING TMP1 FOR ALL CHARACTERS
INSPECT CURABBR
TALLYING TMP2 FOR TRAILING SPACES
SUBTRACT TMP2 FROM TMP1
DISPLAY CURABBR(1:TMP1) WITH NO ADVANCING
DISPLAY "." WITH NO ADVANCING
IF TINDEX < 7 THEN
DISPLAY SPACE WITH NO ADVANCING
ELSE
DISPLAY X"0a" WITH NO ADVANCING
END-IF
ADD 1 TO TINDEX
END-PERFORM
END-IF
END-IF
END-PERFORM
END-READ
ADD 1 TO LINE-NUM
END-PERFORM.
CLOSE DOW.
STOP RUN.
| package main
import(
"bufio"
"fmt"
"os"
"strings"
)
func distinctStrings(strs []string) []string {
len := len(strs)
set := make(map[string]bool, len)
distinct := make([]string, 0, len)
for _, str := range strs {
if !set[str] {
distinct = append(distinct, str)
set[str] = true
}
}
return distinct
}
func takeRunes(s string, n int) string {
i := 0
for j := range s {
if i == n {
return s[:j]
}
i++
}
return s
}
func main() {
file, err := os.Open("days_of_week.txt")
if err != nil {
fmt.Println("Unable to open file.")
return
}
defer file.Close()
reader := bufio.NewReader(file)
lineCount := 0
for {
line, err := reader.ReadString('\n')
if err != nil {
return
}
line = strings.TrimSpace(line)
lineCount++
if line == "" {
fmt.Println()
continue
}
days := strings.Fields(line)
daysLen := len(days)
if (len(days) != 7) {
fmt.Println("There aren't 7 days in line", lineCount)
return
}
if len(distinctStrings(days)) != 7 {
fmt.Println(" β ", line)
continue
}
for abbrevLen := 1; ; abbrevLen++ {
abbrevs := make([]string, daysLen)
for i := 0; i < daysLen; i++ {
abbrevs[i] = takeRunes(days[i], abbrevLen)
}
if len(distinctStrings(abbrevs)) == 7 {
fmt.Printf("%2d %s\n", abbrevLen, line)
break
}
}
}
}
|
Generate a Go translation of this COBOL snippet without changing its computational steps. | IDENTIFICATION DIVISION.
PROGRAM-ID. AUTO-ABBREVIATIONS.
ENVIRONMENT DIVISION.
INPUT-OUTPUT SECTION.
FILE-CONTROL.
SELECT DOW ASSIGN TO "days-of-week.txt"
ORGANIZATION IS LINE SEQUENTIAL.
DATA DIVISION.
FILE SECTION.
FD DOW.
01 DOW-FILE PIC X(200).
WORKING-STORAGE SECTION.
01 DOW-LINE PIC X(200).
01 ENDO PIC 9(1).
01 ENDO2 PIC 9(1).
01 CURDAY PIC X(50).
01 ABPTR PIC 999.
01 LINE-NUM PIC 9(3) VALUE 1.
01 CHARAMT PIC 9(3) VALUE 1.
01 LARGESTCHARAMT PIC 9(3).
01 DAYNUM PIC 9(3) VALUE 1.
01 ABRESTART PIC 9(1).
01 CURABBR PIC X(50).
01 TMP1 PIC 9(3).
01 TMP2 PIC 9(3).
01 TINDEX PIC 9(3) VALUE 1.
01 ABBRLIST.
05 ABBRITEM PIC X(50) OCCURS 7 TIMES.
PROCEDURE DIVISION.
OPEN INPUT DOW.
PERFORM UNTIL ENDO = 1
READ DOW INTO DOW-LINE
AT END MOVE 1 TO ENDO
NOT AT END PERFORM
IF DOW-LINE = "" THEN
DISPLAY ""
ELSE
MOVE 0 TO ENDO2
MOVE 0 TO CHARAMT
PERFORM UNTIL ENDO2 > 0
MOVE 1 TO ABPTR
MOVE 1 TO DAYNUM
MOVE 0 TO ABRESTART
ADD 1 TO CHARAMT
MOVE 1 TO TINDEX
PERFORM 7 TIMES
MOVE SPACE TO ABBRITEM(TINDEX)
ADD 1 TO TINDEX
END-PERFORM
PERFORM 7 TIMES
UNSTRING DOW-LINE DELIMITED BY SPACE
INTO CURDAY
WITH POINTER ABPTR
END-UNSTRING
MOVE 0 TO TMP1
MOVE 0 TO TMP2
INSPECT CURDAY
TALLYING TMP1 FOR ALL CHARACTERS
INSPECT CURDAY
TALLYING TMP2 FOR ALL SPACE
SUBTRACT TMP2 FROM TMP1
IF TMP1 > LARGESTCHARAMT THEN
MOVE TMP1 TO LARGESTCHARAMT
END-IF
IF CURDAY = "" THEN
MOVE 3 TO ENDO2
END-IF
MOVE CURDAY(1:CHARAMT) TO CURABBR
MOVE 1 TO TINDEX
PERFORM 7 TIMES
IF ABBRITEM(TINDEX) = CURABBR THEN
MOVE 1 TO ABRESTART
END-IF
ADD 1 TO TINDEX
END-PERFORM
MOVE CURABBR TO ABBRITEM(DAYNUM)
ADD 1 TO DAYNUM
END-PERFORM
IF ABRESTART = 0 THEN
MOVE 1 TO ENDO2
END-IF
IF CHARAMT > LARGESTCHARAMT THEN
MOVE 2 TO ENDO2
END-IF
END-PERFORM
DISPLAY "Line " LINE-NUM ": " WITH NO ADVANCING
IF ENDO2 = 3 THEN
DISPLAY "Error: not enough " WITH NO ADVANCING
DISPLAY "days"
ELSE IF ENDO2 = 2 THEN
DISPLAY "Error: identical " WITH NO ADVANCING
DISPLAY "days"
ELSE
DISPLAY CHARAMT ": " WITH NO ADVANCING
MOVE 1 TO TINDEX
PERFORM 7 TIMES
MOVE ABBRITEM(TINDEX) TO CURABBR
MOVE 0 TO TMP1
MOVE 0 TO TMP2
INSPECT CURABBR
TALLYING TMP1 FOR ALL CHARACTERS
INSPECT CURABBR
TALLYING TMP2 FOR TRAILING SPACES
SUBTRACT TMP2 FROM TMP1
DISPLAY CURABBR(1:TMP1) WITH NO ADVANCING
DISPLAY "." WITH NO ADVANCING
IF TINDEX < 7 THEN
DISPLAY SPACE WITH NO ADVANCING
ELSE
DISPLAY X"0a" WITH NO ADVANCING
END-IF
ADD 1 TO TINDEX
END-PERFORM
END-IF
END-IF
END-PERFORM
END-READ
ADD 1 TO LINE-NUM
END-PERFORM.
CLOSE DOW.
STOP RUN.
| package main
import(
"bufio"
"fmt"
"os"
"strings"
)
func distinctStrings(strs []string) []string {
len := len(strs)
set := make(map[string]bool, len)
distinct := make([]string, 0, len)
for _, str := range strs {
if !set[str] {
distinct = append(distinct, str)
set[str] = true
}
}
return distinct
}
func takeRunes(s string, n int) string {
i := 0
for j := range s {
if i == n {
return s[:j]
}
i++
}
return s
}
func main() {
file, err := os.Open("days_of_week.txt")
if err != nil {
fmt.Println("Unable to open file.")
return
}
defer file.Close()
reader := bufio.NewReader(file)
lineCount := 0
for {
line, err := reader.ReadString('\n')
if err != nil {
return
}
line = strings.TrimSpace(line)
lineCount++
if line == "" {
fmt.Println()
continue
}
days := strings.Fields(line)
daysLen := len(days)
if (len(days) != 7) {
fmt.Println("There aren't 7 days in line", lineCount)
return
}
if len(distinctStrings(days)) != 7 {
fmt.Println(" β ", line)
continue
}
for abbrevLen := 1; ; abbrevLen++ {
abbrevs := make([]string, daysLen)
for i := 0; i < daysLen; i++ {
abbrevs[i] = takeRunes(days[i], abbrevLen)
}
if len(distinctStrings(abbrevs)) == 7 {
fmt.Printf("%2d %s\n", abbrevLen, line)
break
}
}
}
}
|
Please provide an equivalent version of this REXX code in C. |
parse arg uw
iFID= 'ABBREV_A.TAB'
say 'minimum'
say 'abbrev' center("days of the week", 80)
say 'ββββββ' center("", 80, 'β')
do while lines(iFID)\==0; days=linein(iFID)
minLen= abb(days)
say right(minLen, 4) ' ' days
end
exit
abb: procedure; parse arg x; #=words(x)
if #==0 then return ''
@.=
L=0
do j=1 for #; @.j=word(x, j)
L.j=length(@.j); L= max(L, L.j)
end
do m=1 for L; $=
do k=1 to #; a=left(@.k, m)
if wordpos(a,$)\==0 then iterate M
$=$ a
end
leave m
end
return m
| #include <stdio.h>
#include <stdlib.h>
#include <string.h>
void process(int lineNum, char buffer[]) {
char days[7][64];
int i = 0, d = 0, j = 0;
while (buffer[i] != 0) {
if (buffer[i] == ' ') {
days[d][j] = '\0';
++d;
j = 0;
} else if (buffer[i] == '\n' || buffer[i] == '\r') {
days[d][j] = '\0';
++d;
break;
} else {
days[d][j] = buffer[i];
++j;
}
if (d >= 7) {
printf("There aren't 7 days in line %d\n", lineNum);
return;
}
++i;
}
if (buffer[i] == '\0') {
days[d][j] = '\0';
++d;
}
if (d < 7) {
printf("There aren't 7 days in line %d\n", lineNum);
return;
} else {
int len = 0;
for (len = 1; len < 64; ++len) {
int d1;
for (d1 = 0; d1 < 7; ++d1) {
int d2;
for (d2 = d1 + 1; d2 < 7; ++d2) {
int unique = 0;
for (i = 0; i < len; ++i) {
if (days[d1][i] != days[d2][i]) {
unique = 1;
break;
}
}
if (!unique) {
goto next_length;
}
}
}
printf("%2d ", len);
for (i = 0; i < 7; ++i) {
printf(" %s", days[i]);
}
printf("\n");
return;
next_length: {}
}
}
printf("Failed to find uniqueness within the bounds.");
}
int main() {
char buffer[1024];
int lineNum = 1, len;
FILE *fp;
fp = fopen("days_of_week.txt", "r");
while (1) {
memset(buffer, 0, sizeof(buffer));
fgets(buffer, sizeof(buffer), fp);
len = strlen(buffer);
if (len == 0 || buffer[len - 1] == '\0') {
break;
}
process(lineNum++, buffer);
}
fclose(fp);
return 0;
}
|
Convert this REXX block to C, preserving its control flow and logic. |
parse arg uw
iFID= 'ABBREV_A.TAB'
say 'minimum'
say 'abbrev' center("days of the week", 80)
say 'ββββββ' center("", 80, 'β')
do while lines(iFID)\==0; days=linein(iFID)
minLen= abb(days)
say right(minLen, 4) ' ' days
end
exit
abb: procedure; parse arg x; #=words(x)
if #==0 then return ''
@.=
L=0
do j=1 for #; @.j=word(x, j)
L.j=length(@.j); L= max(L, L.j)
end
do m=1 for L; $=
do k=1 to #; a=left(@.k, m)
if wordpos(a,$)\==0 then iterate M
$=$ a
end
leave m
end
return m
| #include <stdio.h>
#include <stdlib.h>
#include <string.h>
void process(int lineNum, char buffer[]) {
char days[7][64];
int i = 0, d = 0, j = 0;
while (buffer[i] != 0) {
if (buffer[i] == ' ') {
days[d][j] = '\0';
++d;
j = 0;
} else if (buffer[i] == '\n' || buffer[i] == '\r') {
days[d][j] = '\0';
++d;
break;
} else {
days[d][j] = buffer[i];
++j;
}
if (d >= 7) {
printf("There aren't 7 days in line %d\n", lineNum);
return;
}
++i;
}
if (buffer[i] == '\0') {
days[d][j] = '\0';
++d;
}
if (d < 7) {
printf("There aren't 7 days in line %d\n", lineNum);
return;
} else {
int len = 0;
for (len = 1; len < 64; ++len) {
int d1;
for (d1 = 0; d1 < 7; ++d1) {
int d2;
for (d2 = d1 + 1; d2 < 7; ++d2) {
int unique = 0;
for (i = 0; i < len; ++i) {
if (days[d1][i] != days[d2][i]) {
unique = 1;
break;
}
}
if (!unique) {
goto next_length;
}
}
}
printf("%2d ", len);
for (i = 0; i < 7; ++i) {
printf(" %s", days[i]);
}
printf("\n");
return;
next_length: {}
}
}
printf("Failed to find uniqueness within the bounds.");
}
int main() {
char buffer[1024];
int lineNum = 1, len;
FILE *fp;
fp = fopen("days_of_week.txt", "r");
while (1) {
memset(buffer, 0, sizeof(buffer));
fgets(buffer, sizeof(buffer), fp);
len = strlen(buffer);
if (len == 0 || buffer[len - 1] == '\0') {
break;
}
process(lineNum++, buffer);
}
fclose(fp);
return 0;
}
|
Please provide an equivalent version of this REXX code in C#. |
parse arg uw
iFID= 'ABBREV_A.TAB'
say 'minimum'
say 'abbrev' center("days of the week", 80)
say 'ββββββ' center("", 80, 'β')
do while lines(iFID)\==0; days=linein(iFID)
minLen= abb(days)
say right(minLen, 4) ' ' days
end
exit
abb: procedure; parse arg x; #=words(x)
if #==0 then return ''
@.=
L=0
do j=1 for #; @.j=word(x, j)
L.j=length(@.j); L= max(L, L.j)
end
do m=1 for L; $=
do k=1 to #; a=left(@.k, m)
if wordpos(a,$)\==0 then iterate M
$=$ a
end
leave m
end
return m
| using System;
using System.Collections.Generic;
namespace Abbreviations {
class Program {
static void Main(string[] args) {
string[] lines = System.IO.File.ReadAllLines("days_of_week.txt");
int i = 0;
foreach (string line in lines) {
i++;
if (line.Length > 0) {
var days = line.Split();
if (days.Length != 7) {
throw new Exception("There aren't 7 days in line " + i);
}
Dictionary<string, int> temp = new Dictionary<string, int>();
foreach (string day in days) {
if (temp.ContainsKey(day)) {
Console.WriteLine(" β {0}", line);
continue;
}
temp.Add(day, 1);
}
int len = 1;
while (true) {
temp.Clear();
foreach(string day in days) {
string key;
if (len < day.Length) {
key = day.Substring(0, len);
} else {
key = day;
}
if (temp.ContainsKey(key)) {
break;
}
temp.Add(key, 1);
}
if (temp.Count == 7) {
Console.WriteLine("{0,2:D} {1}", len, line);
break;
}
len++;
}
}
}
}
}
}
|
Write the same code in C# as shown below in REXX. |
parse arg uw
iFID= 'ABBREV_A.TAB'
say 'minimum'
say 'abbrev' center("days of the week", 80)
say 'ββββββ' center("", 80, 'β')
do while lines(iFID)\==0; days=linein(iFID)
minLen= abb(days)
say right(minLen, 4) ' ' days
end
exit
abb: procedure; parse arg x; #=words(x)
if #==0 then return ''
@.=
L=0
do j=1 for #; @.j=word(x, j)
L.j=length(@.j); L= max(L, L.j)
end
do m=1 for L; $=
do k=1 to #; a=left(@.k, m)
if wordpos(a,$)\==0 then iterate M
$=$ a
end
leave m
end
return m
| using System;
using System.Collections.Generic;
namespace Abbreviations {
class Program {
static void Main(string[] args) {
string[] lines = System.IO.File.ReadAllLines("days_of_week.txt");
int i = 0;
foreach (string line in lines) {
i++;
if (line.Length > 0) {
var days = line.Split();
if (days.Length != 7) {
throw new Exception("There aren't 7 days in line " + i);
}
Dictionary<string, int> temp = new Dictionary<string, int>();
foreach (string day in days) {
if (temp.ContainsKey(day)) {
Console.WriteLine(" β {0}", line);
continue;
}
temp.Add(day, 1);
}
int len = 1;
while (true) {
temp.Clear();
foreach(string day in days) {
string key;
if (len < day.Length) {
key = day.Substring(0, len);
} else {
key = day;
}
if (temp.ContainsKey(key)) {
break;
}
temp.Add(key, 1);
}
if (temp.Count == 7) {
Console.WriteLine("{0,2:D} {1}", len, line);
break;
}
len++;
}
}
}
}
}
}
|
Convert this REXX snippet to C++ and keep its semantics consistent. |
parse arg uw
iFID= 'ABBREV_A.TAB'
say 'minimum'
say 'abbrev' center("days of the week", 80)
say 'ββββββ' center("", 80, 'β')
do while lines(iFID)\==0; days=linein(iFID)
minLen= abb(days)
say right(minLen, 4) ' ' days
end
exit
abb: procedure; parse arg x; #=words(x)
if #==0 then return ''
@.=
L=0
do j=1 for #; @.j=word(x, j)
L.j=length(@.j); L= max(L, L.j)
end
do m=1 for L; $=
do k=1 to #; a=left(@.k, m)
if wordpos(a,$)\==0 then iterate M
$=$ a
end
leave m
end
return m
| #include <iomanip>
#include <iostream>
#include <fstream>
#include <map>
#include <sstream>
#include <string>
#include <vector>
std::vector<std::string> split(const std::string& str, char delimiter) {
std::vector<std::string> tokens;
std::string token;
std::istringstream tokenStream(str);
while (std::getline(tokenStream, token, delimiter)) {
tokens.push_back(token);
}
return tokens;
}
int main() {
using namespace std;
string line;
int i = 0;
ifstream in("days_of_week.txt");
if (in.is_open()) {
while (getline(in, line)) {
i++;
if (line.empty()) {
continue;
}
auto days = split(line, ' ');
if (days.size() != 7) {
throw std::runtime_error("There aren't 7 days in line " + i);
}
map<string, int> temp;
for (auto& day : days) {
if (temp.find(day) != temp.end()) {
cerr << " β " << line << '\n';
continue;
}
temp[day] = 1;
}
int len = 1;
while (true) {
temp.clear();
for (auto& day : days) {
string key = day.substr(0, len);
if (temp.find(key) != temp.end()) {
break;
}
temp[key] = 1;
}
if (temp.size() == 7) {
cout << setw(2) << len << " " << line << '\n';
break;
}
len++;
}
}
}
return 0;
}
|
Maintain the same structure and functionality when rewriting this code in C++. |
parse arg uw
iFID= 'ABBREV_A.TAB'
say 'minimum'
say 'abbrev' center("days of the week", 80)
say 'ββββββ' center("", 80, 'β')
do while lines(iFID)\==0; days=linein(iFID)
minLen= abb(days)
say right(minLen, 4) ' ' days
end
exit
abb: procedure; parse arg x; #=words(x)
if #==0 then return ''
@.=
L=0
do j=1 for #; @.j=word(x, j)
L.j=length(@.j); L= max(L, L.j)
end
do m=1 for L; $=
do k=1 to #; a=left(@.k, m)
if wordpos(a,$)\==0 then iterate M
$=$ a
end
leave m
end
return m
| #include <iomanip>
#include <iostream>
#include <fstream>
#include <map>
#include <sstream>
#include <string>
#include <vector>
std::vector<std::string> split(const std::string& str, char delimiter) {
std::vector<std::string> tokens;
std::string token;
std::istringstream tokenStream(str);
while (std::getline(tokenStream, token, delimiter)) {
tokens.push_back(token);
}
return tokens;
}
int main() {
using namespace std;
string line;
int i = 0;
ifstream in("days_of_week.txt");
if (in.is_open()) {
while (getline(in, line)) {
i++;
if (line.empty()) {
continue;
}
auto days = split(line, ' ');
if (days.size() != 7) {
throw std::runtime_error("There aren't 7 days in line " + i);
}
map<string, int> temp;
for (auto& day : days) {
if (temp.find(day) != temp.end()) {
cerr << " β " << line << '\n';
continue;
}
temp[day] = 1;
}
int len = 1;
while (true) {
temp.clear();
for (auto& day : days) {
string key = day.substr(0, len);
if (temp.find(key) != temp.end()) {
break;
}
temp[key] = 1;
}
if (temp.size() == 7) {
cout << setw(2) << len << " " << line << '\n';
break;
}
len++;
}
}
}
return 0;
}
|
Convert the following code from REXX to Java, ensuring the logic remains intact. |
parse arg uw
iFID= 'ABBREV_A.TAB'
say 'minimum'
say 'abbrev' center("days of the week", 80)
say 'ββββββ' center("", 80, 'β')
do while lines(iFID)\==0; days=linein(iFID)
minLen= abb(days)
say right(minLen, 4) ' ' days
end
exit
abb: procedure; parse arg x; #=words(x)
if #==0 then return ''
@.=
L=0
do j=1 for #; @.j=word(x, j)
L.j=length(@.j); L= max(L, L.j)
end
do m=1 for L; $=
do k=1 to #; a=left(@.k, m)
if wordpos(a,$)\==0 then iterate M
$=$ a
end
leave m
end
return m
| import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class Abbreviations {
public static void main(String[] args) throws IOException {
Path path = Paths.get("days_of_week.txt");
List<String> readAllLines = Files.readAllLines(path);
for (int i = 0; i < readAllLines.size(); i++) {
String line = readAllLines.get(i);
if (line.length() == 0) continue;
String[] days = line.split(" ");
if (days.length != 7) throw new RuntimeException("There aren't 7 days on line " + (i + 1));
Map<String, Integer> temp = new HashMap<>();
for (String day : days) {
Integer count = temp.getOrDefault(day, 0);
temp.put(day, count + 1);
}
if (temp.size() < 7) {
System.out.print(" β ");
System.out.println(line);
continue;
}
int len = 1;
while (true) {
temp.clear();
for (String day : days) {
String sd;
if (len >= day.length()) {
sd = day;
} else {
sd = day.substring(0, len);
}
Integer count = temp.getOrDefault(sd, 0);
temp.put(sd, count + 1);
}
if (temp.size() == 7) {
System.out.printf("%2d %s\n", len, line);
break;
}
len++;
}
}
}
}
|
Rewrite this program in Java while keeping its functionality equivalent to the REXX version. |
parse arg uw
iFID= 'ABBREV_A.TAB'
say 'minimum'
say 'abbrev' center("days of the week", 80)
say 'ββββββ' center("", 80, 'β')
do while lines(iFID)\==0; days=linein(iFID)
minLen= abb(days)
say right(minLen, 4) ' ' days
end
exit
abb: procedure; parse arg x; #=words(x)
if #==0 then return ''
@.=
L=0
do j=1 for #; @.j=word(x, j)
L.j=length(@.j); L= max(L, L.j)
end
do m=1 for L; $=
do k=1 to #; a=left(@.k, m)
if wordpos(a,$)\==0 then iterate M
$=$ a
end
leave m
end
return m
| import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class Abbreviations {
public static void main(String[] args) throws IOException {
Path path = Paths.get("days_of_week.txt");
List<String> readAllLines = Files.readAllLines(path);
for (int i = 0; i < readAllLines.size(); i++) {
String line = readAllLines.get(i);
if (line.length() == 0) continue;
String[] days = line.split(" ");
if (days.length != 7) throw new RuntimeException("There aren't 7 days on line " + (i + 1));
Map<String, Integer> temp = new HashMap<>();
for (String day : days) {
Integer count = temp.getOrDefault(day, 0);
temp.put(day, count + 1);
}
if (temp.size() < 7) {
System.out.print(" β ");
System.out.println(line);
continue;
}
int len = 1;
while (true) {
temp.clear();
for (String day : days) {
String sd;
if (len >= day.length()) {
sd = day;
} else {
sd = day.substring(0, len);
}
Integer count = temp.getOrDefault(sd, 0);
temp.put(sd, count + 1);
}
if (temp.size() == 7) {
System.out.printf("%2d %s\n", len, line);
break;
}
len++;
}
}
}
}
|
Ensure the translated Python code behaves exactly like the original REXX snippet. |
parse arg uw
iFID= 'ABBREV_A.TAB'
say 'minimum'
say 'abbrev' center("days of the week", 80)
say 'ββββββ' center("", 80, 'β')
do while lines(iFID)\==0; days=linein(iFID)
minLen= abb(days)
say right(minLen, 4) ' ' days
end
exit
abb: procedure; parse arg x; #=words(x)
if #==0 then return ''
@.=
L=0
do j=1 for #; @.j=word(x, j)
L.j=length(@.j); L= max(L, L.j)
end
do m=1 for L; $=
do k=1 to #; a=left(@.k, m)
if wordpos(a,$)\==0 then iterate M
$=$ a
end
leave m
end
return m
| def shortest_abbreviation_length(line, list_size):
words = line.split()
word_count = len(words)
if word_count != list_size:
raise ValueError(f'Not enough entries, expected {list_size} found {word_count}')
abbreviation_length = 1
abbreviations = set()
while(True):
abbreviations = {word[:abbreviation_length] for word in words}
if len(abbreviations) == list_size:
return abbreviation_length
abbreviation_length += 1
abbreviations.clear()
def automatic_abbreviations(filename, words_per_line):
with open(filename) as file:
for line in file:
line = line.rstrip()
if len(line) > 0:
length = shortest_abbreviation_length(line, words_per_line)
print(f'{length:2} {line}')
else:
print()
automatic_abbreviations('daysOfWeek.txt', 7)
|
Translate this program into Python but keep the logic exactly as in REXX. |
parse arg uw
iFID= 'ABBREV_A.TAB'
say 'minimum'
say 'abbrev' center("days of the week", 80)
say 'ββββββ' center("", 80, 'β')
do while lines(iFID)\==0; days=linein(iFID)
minLen= abb(days)
say right(minLen, 4) ' ' days
end
exit
abb: procedure; parse arg x; #=words(x)
if #==0 then return ''
@.=
L=0
do j=1 for #; @.j=word(x, j)
L.j=length(@.j); L= max(L, L.j)
end
do m=1 for L; $=
do k=1 to #; a=left(@.k, m)
if wordpos(a,$)\==0 then iterate M
$=$ a
end
leave m
end
return m
| def shortest_abbreviation_length(line, list_size):
words = line.split()
word_count = len(words)
if word_count != list_size:
raise ValueError(f'Not enough entries, expected {list_size} found {word_count}')
abbreviation_length = 1
abbreviations = set()
while(True):
abbreviations = {word[:abbreviation_length] for word in words}
if len(abbreviations) == list_size:
return abbreviation_length
abbreviation_length += 1
abbreviations.clear()
def automatic_abbreviations(filename, words_per_line):
with open(filename) as file:
for line in file:
line = line.rstrip()
if len(line) > 0:
length = shortest_abbreviation_length(line, words_per_line)
print(f'{length:2} {line}')
else:
print()
automatic_abbreviations('daysOfWeek.txt', 7)
|
Generate a VB translation of this REXX snippet without changing its computational steps. |
parse arg uw
iFID= 'ABBREV_A.TAB'
say 'minimum'
say 'abbrev' center("days of the week", 80)
say 'ββββββ' center("", 80, 'β')
do while lines(iFID)\==0; days=linein(iFID)
minLen= abb(days)
say right(minLen, 4) ' ' days
end
exit
abb: procedure; parse arg x; #=words(x)
if #==0 then return ''
@.=
L=0
do j=1 for #; @.j=word(x, j)
L.j=length(@.j); L= max(L, L.j)
end
do m=1 for L; $=
do k=1 to #; a=left(@.k, m)
if wordpos(a,$)\==0 then iterate M
$=$ a
end
leave m
end
return m
| Function MinimalLenght(strLine As String) As Integer
Dim myVar As Variant, I As Integer, Flag As Boolean, myColl As Collection, Count As Integer
myVar = Split(strLine, " ")
Count = 0
Do
Set myColl = New Collection
Count = Count + 1
On Error Resume Next
Do
myColl.Add Left$(myVar(I), Count), Left$(myVar(I), Count)
I = I + 1
Loop While Err.Number = 0 And I <= UBound(myVar)
Flag = Err.Number = 0
On Error GoTo 0
I = 0
Set myColl = Nothing
Loop While Not Flag
MinimalLenght = Count
End Function
|
Change the programming language of this snippet from REXX to VB without modifying what it does. |
parse arg uw
iFID= 'ABBREV_A.TAB'
say 'minimum'
say 'abbrev' center("days of the week", 80)
say 'ββββββ' center("", 80, 'β')
do while lines(iFID)\==0; days=linein(iFID)
minLen= abb(days)
say right(minLen, 4) ' ' days
end
exit
abb: procedure; parse arg x; #=words(x)
if #==0 then return ''
@.=
L=0
do j=1 for #; @.j=word(x, j)
L.j=length(@.j); L= max(L, L.j)
end
do m=1 for L; $=
do k=1 to #; a=left(@.k, m)
if wordpos(a,$)\==0 then iterate M
$=$ a
end
leave m
end
return m
| Function MinimalLenght(strLine As String) As Integer
Dim myVar As Variant, I As Integer, Flag As Boolean, myColl As Collection, Count As Integer
myVar = Split(strLine, " ")
Count = 0
Do
Set myColl = New Collection
Count = Count + 1
On Error Resume Next
Do
myColl.Add Left$(myVar(I), Count), Left$(myVar(I), Count)
I = I + 1
Loop While Err.Number = 0 And I <= UBound(myVar)
Flag = Err.Number = 0
On Error GoTo 0
I = 0
Set myColl = Nothing
Loop While Not Flag
MinimalLenght = Count
End Function
|
Produce a functionally identical Go code for the snippet given in REXX. |
parse arg uw
iFID= 'ABBREV_A.TAB'
say 'minimum'
say 'abbrev' center("days of the week", 80)
say 'ββββββ' center("", 80, 'β')
do while lines(iFID)\==0; days=linein(iFID)
minLen= abb(days)
say right(minLen, 4) ' ' days
end
exit
abb: procedure; parse arg x; #=words(x)
if #==0 then return ''
@.=
L=0
do j=1 for #; @.j=word(x, j)
L.j=length(@.j); L= max(L, L.j)
end
do m=1 for L; $=
do k=1 to #; a=left(@.k, m)
if wordpos(a,$)\==0 then iterate M
$=$ a
end
leave m
end
return m
| package main
import(
"bufio"
"fmt"
"os"
"strings"
)
func distinctStrings(strs []string) []string {
len := len(strs)
set := make(map[string]bool, len)
distinct := make([]string, 0, len)
for _, str := range strs {
if !set[str] {
distinct = append(distinct, str)
set[str] = true
}
}
return distinct
}
func takeRunes(s string, n int) string {
i := 0
for j := range s {
if i == n {
return s[:j]
}
i++
}
return s
}
func main() {
file, err := os.Open("days_of_week.txt")
if err != nil {
fmt.Println("Unable to open file.")
return
}
defer file.Close()
reader := bufio.NewReader(file)
lineCount := 0
for {
line, err := reader.ReadString('\n')
if err != nil {
return
}
line = strings.TrimSpace(line)
lineCount++
if line == "" {
fmt.Println()
continue
}
days := strings.Fields(line)
daysLen := len(days)
if (len(days) != 7) {
fmt.Println("There aren't 7 days in line", lineCount)
return
}
if len(distinctStrings(days)) != 7 {
fmt.Println(" β ", line)
continue
}
for abbrevLen := 1; ; abbrevLen++ {
abbrevs := make([]string, daysLen)
for i := 0; i < daysLen; i++ {
abbrevs[i] = takeRunes(days[i], abbrevLen)
}
if len(distinctStrings(abbrevs)) == 7 {
fmt.Printf("%2d %s\n", abbrevLen, line)
break
}
}
}
}
|
Maintain the same structure and functionality when rewriting this code in Go. |
parse arg uw
iFID= 'ABBREV_A.TAB'
say 'minimum'
say 'abbrev' center("days of the week", 80)
say 'ββββββ' center("", 80, 'β')
do while lines(iFID)\==0; days=linein(iFID)
minLen= abb(days)
say right(minLen, 4) ' ' days
end
exit
abb: procedure; parse arg x; #=words(x)
if #==0 then return ''
@.=
L=0
do j=1 for #; @.j=word(x, j)
L.j=length(@.j); L= max(L, L.j)
end
do m=1 for L; $=
do k=1 to #; a=left(@.k, m)
if wordpos(a,$)\==0 then iterate M
$=$ a
end
leave m
end
return m
| package main
import(
"bufio"
"fmt"
"os"
"strings"
)
func distinctStrings(strs []string) []string {
len := len(strs)
set := make(map[string]bool, len)
distinct := make([]string, 0, len)
for _, str := range strs {
if !set[str] {
distinct = append(distinct, str)
set[str] = true
}
}
return distinct
}
func takeRunes(s string, n int) string {
i := 0
for j := range s {
if i == n {
return s[:j]
}
i++
}
return s
}
func main() {
file, err := os.Open("days_of_week.txt")
if err != nil {
fmt.Println("Unable to open file.")
return
}
defer file.Close()
reader := bufio.NewReader(file)
lineCount := 0
for {
line, err := reader.ReadString('\n')
if err != nil {
return
}
line = strings.TrimSpace(line)
lineCount++
if line == "" {
fmt.Println()
continue
}
days := strings.Fields(line)
daysLen := len(days)
if (len(days) != 7) {
fmt.Println("There aren't 7 days in line", lineCount)
return
}
if len(distinctStrings(days)) != 7 {
fmt.Println(" β ", line)
continue
}
for abbrevLen := 1; ; abbrevLen++ {
abbrevs := make([]string, daysLen)
for i := 0; i < daysLen; i++ {
abbrevs[i] = takeRunes(days[i], abbrevLen)
}
if len(distinctStrings(abbrevs)) == 7 {
fmt.Printf("%2d %s\n", abbrevLen, line)
break
}
}
}
}
|
Rewrite the snippet below in C so it works the same as the original Ruby code. | require "abbrev"
File.read("daynames.txt").each_line do |line|
next if line.strip.empty?
abbr = line.split.abbrev.invert
puts "Minimum size:
end
| #include <stdio.h>
#include <stdlib.h>
#include <string.h>
void process(int lineNum, char buffer[]) {
char days[7][64];
int i = 0, d = 0, j = 0;
while (buffer[i] != 0) {
if (buffer[i] == ' ') {
days[d][j] = '\0';
++d;
j = 0;
} else if (buffer[i] == '\n' || buffer[i] == '\r') {
days[d][j] = '\0';
++d;
break;
} else {
days[d][j] = buffer[i];
++j;
}
if (d >= 7) {
printf("There aren't 7 days in line %d\n", lineNum);
return;
}
++i;
}
if (buffer[i] == '\0') {
days[d][j] = '\0';
++d;
}
if (d < 7) {
printf("There aren't 7 days in line %d\n", lineNum);
return;
} else {
int len = 0;
for (len = 1; len < 64; ++len) {
int d1;
for (d1 = 0; d1 < 7; ++d1) {
int d2;
for (d2 = d1 + 1; d2 < 7; ++d2) {
int unique = 0;
for (i = 0; i < len; ++i) {
if (days[d1][i] != days[d2][i]) {
unique = 1;
break;
}
}
if (!unique) {
goto next_length;
}
}
}
printf("%2d ", len);
for (i = 0; i < 7; ++i) {
printf(" %s", days[i]);
}
printf("\n");
return;
next_length: {}
}
}
printf("Failed to find uniqueness within the bounds.");
}
int main() {
char buffer[1024];
int lineNum = 1, len;
FILE *fp;
fp = fopen("days_of_week.txt", "r");
while (1) {
memset(buffer, 0, sizeof(buffer));
fgets(buffer, sizeof(buffer), fp);
len = strlen(buffer);
if (len == 0 || buffer[len - 1] == '\0') {
break;
}
process(lineNum++, buffer);
}
fclose(fp);
return 0;
}
|
Produce a language-to-language conversion: from Ruby to C, same semantics. | require "abbrev"
File.read("daynames.txt").each_line do |line|
next if line.strip.empty?
abbr = line.split.abbrev.invert
puts "Minimum size:
end
| #include <stdio.h>
#include <stdlib.h>
#include <string.h>
void process(int lineNum, char buffer[]) {
char days[7][64];
int i = 0, d = 0, j = 0;
while (buffer[i] != 0) {
if (buffer[i] == ' ') {
days[d][j] = '\0';
++d;
j = 0;
} else if (buffer[i] == '\n' || buffer[i] == '\r') {
days[d][j] = '\0';
++d;
break;
} else {
days[d][j] = buffer[i];
++j;
}
if (d >= 7) {
printf("There aren't 7 days in line %d\n", lineNum);
return;
}
++i;
}
if (buffer[i] == '\0') {
days[d][j] = '\0';
++d;
}
if (d < 7) {
printf("There aren't 7 days in line %d\n", lineNum);
return;
} else {
int len = 0;
for (len = 1; len < 64; ++len) {
int d1;
for (d1 = 0; d1 < 7; ++d1) {
int d2;
for (d2 = d1 + 1; d2 < 7; ++d2) {
int unique = 0;
for (i = 0; i < len; ++i) {
if (days[d1][i] != days[d2][i]) {
unique = 1;
break;
}
}
if (!unique) {
goto next_length;
}
}
}
printf("%2d ", len);
for (i = 0; i < 7; ++i) {
printf(" %s", days[i]);
}
printf("\n");
return;
next_length: {}
}
}
printf("Failed to find uniqueness within the bounds.");
}
int main() {
char buffer[1024];
int lineNum = 1, len;
FILE *fp;
fp = fopen("days_of_week.txt", "r");
while (1) {
memset(buffer, 0, sizeof(buffer));
fgets(buffer, sizeof(buffer), fp);
len = strlen(buffer);
if (len == 0 || buffer[len - 1] == '\0') {
break;
}
process(lineNum++, buffer);
}
fclose(fp);
return 0;
}
|
Generate a C# translation of this Ruby snippet without changing its computational steps. | require "abbrev"
File.read("daynames.txt").each_line do |line|
next if line.strip.empty?
abbr = line.split.abbrev.invert
puts "Minimum size:
end
| using System;
using System.Collections.Generic;
namespace Abbreviations {
class Program {
static void Main(string[] args) {
string[] lines = System.IO.File.ReadAllLines("days_of_week.txt");
int i = 0;
foreach (string line in lines) {
i++;
if (line.Length > 0) {
var days = line.Split();
if (days.Length != 7) {
throw new Exception("There aren't 7 days in line " + i);
}
Dictionary<string, int> temp = new Dictionary<string, int>();
foreach (string day in days) {
if (temp.ContainsKey(day)) {
Console.WriteLine(" β {0}", line);
continue;
}
temp.Add(day, 1);
}
int len = 1;
while (true) {
temp.Clear();
foreach(string day in days) {
string key;
if (len < day.Length) {
key = day.Substring(0, len);
} else {
key = day;
}
if (temp.ContainsKey(key)) {
break;
}
temp.Add(key, 1);
}
if (temp.Count == 7) {
Console.WriteLine("{0,2:D} {1}", len, line);
break;
}
len++;
}
}
}
}
}
}
|
Rewrite this program in C# while keeping its functionality equivalent to the Ruby version. | require "abbrev"
File.read("daynames.txt").each_line do |line|
next if line.strip.empty?
abbr = line.split.abbrev.invert
puts "Minimum size:
end
| using System;
using System.Collections.Generic;
namespace Abbreviations {
class Program {
static void Main(string[] args) {
string[] lines = System.IO.File.ReadAllLines("days_of_week.txt");
int i = 0;
foreach (string line in lines) {
i++;
if (line.Length > 0) {
var days = line.Split();
if (days.Length != 7) {
throw new Exception("There aren't 7 days in line " + i);
}
Dictionary<string, int> temp = new Dictionary<string, int>();
foreach (string day in days) {
if (temp.ContainsKey(day)) {
Console.WriteLine(" β {0}", line);
continue;
}
temp.Add(day, 1);
}
int len = 1;
while (true) {
temp.Clear();
foreach(string day in days) {
string key;
if (len < day.Length) {
key = day.Substring(0, len);
} else {
key = day;
}
if (temp.ContainsKey(key)) {
break;
}
temp.Add(key, 1);
}
if (temp.Count == 7) {
Console.WriteLine("{0,2:D} {1}", len, line);
break;
}
len++;
}
}
}
}
}
}
|
Produce a functionally identical C++ code for the snippet given in Ruby. | require "abbrev"
File.read("daynames.txt").each_line do |line|
next if line.strip.empty?
abbr = line.split.abbrev.invert
puts "Minimum size:
end
| #include <iomanip>
#include <iostream>
#include <fstream>
#include <map>
#include <sstream>
#include <string>
#include <vector>
std::vector<std::string> split(const std::string& str, char delimiter) {
std::vector<std::string> tokens;
std::string token;
std::istringstream tokenStream(str);
while (std::getline(tokenStream, token, delimiter)) {
tokens.push_back(token);
}
return tokens;
}
int main() {
using namespace std;
string line;
int i = 0;
ifstream in("days_of_week.txt");
if (in.is_open()) {
while (getline(in, line)) {
i++;
if (line.empty()) {
continue;
}
auto days = split(line, ' ');
if (days.size() != 7) {
throw std::runtime_error("There aren't 7 days in line " + i);
}
map<string, int> temp;
for (auto& day : days) {
if (temp.find(day) != temp.end()) {
cerr << " β " << line << '\n';
continue;
}
temp[day] = 1;
}
int len = 1;
while (true) {
temp.clear();
for (auto& day : days) {
string key = day.substr(0, len);
if (temp.find(key) != temp.end()) {
break;
}
temp[key] = 1;
}
if (temp.size() == 7) {
cout << setw(2) << len << " " << line << '\n';
break;
}
len++;
}
}
}
return 0;
}
|
Generate a C++ translation of this Ruby snippet without changing its computational steps. | require "abbrev"
File.read("daynames.txt").each_line do |line|
next if line.strip.empty?
abbr = line.split.abbrev.invert
puts "Minimum size:
end
| #include <iomanip>
#include <iostream>
#include <fstream>
#include <map>
#include <sstream>
#include <string>
#include <vector>
std::vector<std::string> split(const std::string& str, char delimiter) {
std::vector<std::string> tokens;
std::string token;
std::istringstream tokenStream(str);
while (std::getline(tokenStream, token, delimiter)) {
tokens.push_back(token);
}
return tokens;
}
int main() {
using namespace std;
string line;
int i = 0;
ifstream in("days_of_week.txt");
if (in.is_open()) {
while (getline(in, line)) {
i++;
if (line.empty()) {
continue;
}
auto days = split(line, ' ');
if (days.size() != 7) {
throw std::runtime_error("There aren't 7 days in line " + i);
}
map<string, int> temp;
for (auto& day : days) {
if (temp.find(day) != temp.end()) {
cerr << " β " << line << '\n';
continue;
}
temp[day] = 1;
}
int len = 1;
while (true) {
temp.clear();
for (auto& day : days) {
string key = day.substr(0, len);
if (temp.find(key) != temp.end()) {
break;
}
temp[key] = 1;
}
if (temp.size() == 7) {
cout << setw(2) << len << " " << line << '\n';
break;
}
len++;
}
}
}
return 0;
}
|
Convert the following code from Ruby to Java, ensuring the logic remains intact. | require "abbrev"
File.read("daynames.txt").each_line do |line|
next if line.strip.empty?
abbr = line.split.abbrev.invert
puts "Minimum size:
end
| import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class Abbreviations {
public static void main(String[] args) throws IOException {
Path path = Paths.get("days_of_week.txt");
List<String> readAllLines = Files.readAllLines(path);
for (int i = 0; i < readAllLines.size(); i++) {
String line = readAllLines.get(i);
if (line.length() == 0) continue;
String[] days = line.split(" ");
if (days.length != 7) throw new RuntimeException("There aren't 7 days on line " + (i + 1));
Map<String, Integer> temp = new HashMap<>();
for (String day : days) {
Integer count = temp.getOrDefault(day, 0);
temp.put(day, count + 1);
}
if (temp.size() < 7) {
System.out.print(" β ");
System.out.println(line);
continue;
}
int len = 1;
while (true) {
temp.clear();
for (String day : days) {
String sd;
if (len >= day.length()) {
sd = day;
} else {
sd = day.substring(0, len);
}
Integer count = temp.getOrDefault(sd, 0);
temp.put(sd, count + 1);
}
if (temp.size() == 7) {
System.out.printf("%2d %s\n", len, line);
break;
}
len++;
}
}
}
}
|
Generate an equivalent Java version of this Ruby code. | require "abbrev"
File.read("daynames.txt").each_line do |line|
next if line.strip.empty?
abbr = line.split.abbrev.invert
puts "Minimum size:
end
| import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class Abbreviations {
public static void main(String[] args) throws IOException {
Path path = Paths.get("days_of_week.txt");
List<String> readAllLines = Files.readAllLines(path);
for (int i = 0; i < readAllLines.size(); i++) {
String line = readAllLines.get(i);
if (line.length() == 0) continue;
String[] days = line.split(" ");
if (days.length != 7) throw new RuntimeException("There aren't 7 days on line " + (i + 1));
Map<String, Integer> temp = new HashMap<>();
for (String day : days) {
Integer count = temp.getOrDefault(day, 0);
temp.put(day, count + 1);
}
if (temp.size() < 7) {
System.out.print(" β ");
System.out.println(line);
continue;
}
int len = 1;
while (true) {
temp.clear();
for (String day : days) {
String sd;
if (len >= day.length()) {
sd = day;
} else {
sd = day.substring(0, len);
}
Integer count = temp.getOrDefault(sd, 0);
temp.put(sd, count + 1);
}
if (temp.size() == 7) {
System.out.printf("%2d %s\n", len, line);
break;
}
len++;
}
}
}
}
|
Rewrite the snippet below in Python so it works the same as the original Ruby code. | require "abbrev"
File.read("daynames.txt").each_line do |line|
next if line.strip.empty?
abbr = line.split.abbrev.invert
puts "Minimum size:
end
| def shortest_abbreviation_length(line, list_size):
words = line.split()
word_count = len(words)
if word_count != list_size:
raise ValueError(f'Not enough entries, expected {list_size} found {word_count}')
abbreviation_length = 1
abbreviations = set()
while(True):
abbreviations = {word[:abbreviation_length] for word in words}
if len(abbreviations) == list_size:
return abbreviation_length
abbreviation_length += 1
abbreviations.clear()
def automatic_abbreviations(filename, words_per_line):
with open(filename) as file:
for line in file:
line = line.rstrip()
if len(line) > 0:
length = shortest_abbreviation_length(line, words_per_line)
print(f'{length:2} {line}')
else:
print()
automatic_abbreviations('daysOfWeek.txt', 7)
|
Preserve the algorithm and functionality while converting the code from Ruby to Python. | require "abbrev"
File.read("daynames.txt").each_line do |line|
next if line.strip.empty?
abbr = line.split.abbrev.invert
puts "Minimum size:
end
| def shortest_abbreviation_length(line, list_size):
words = line.split()
word_count = len(words)
if word_count != list_size:
raise ValueError(f'Not enough entries, expected {list_size} found {word_count}')
abbreviation_length = 1
abbreviations = set()
while(True):
abbreviations = {word[:abbreviation_length] for word in words}
if len(abbreviations) == list_size:
return abbreviation_length
abbreviation_length += 1
abbreviations.clear()
def automatic_abbreviations(filename, words_per_line):
with open(filename) as file:
for line in file:
line = line.rstrip()
if len(line) > 0:
length = shortest_abbreviation_length(line, words_per_line)
print(f'{length:2} {line}')
else:
print()
automatic_abbreviations('daysOfWeek.txt', 7)
|
Produce a functionally identical VB code for the snippet given in Ruby. | require "abbrev"
File.read("daynames.txt").each_line do |line|
next if line.strip.empty?
abbr = line.split.abbrev.invert
puts "Minimum size:
end
| Function MinimalLenght(strLine As String) As Integer
Dim myVar As Variant, I As Integer, Flag As Boolean, myColl As Collection, Count As Integer
myVar = Split(strLine, " ")
Count = 0
Do
Set myColl = New Collection
Count = Count + 1
On Error Resume Next
Do
myColl.Add Left$(myVar(I), Count), Left$(myVar(I), Count)
I = I + 1
Loop While Err.Number = 0 And I <= UBound(myVar)
Flag = Err.Number = 0
On Error GoTo 0
I = 0
Set myColl = Nothing
Loop While Not Flag
MinimalLenght = Count
End Function
|
Preserve the algorithm and functionality while converting the code from Ruby to VB. | require "abbrev"
File.read("daynames.txt").each_line do |line|
next if line.strip.empty?
abbr = line.split.abbrev.invert
puts "Minimum size:
end
| Function MinimalLenght(strLine As String) As Integer
Dim myVar As Variant, I As Integer, Flag As Boolean, myColl As Collection, Count As Integer
myVar = Split(strLine, " ")
Count = 0
Do
Set myColl = New Collection
Count = Count + 1
On Error Resume Next
Do
myColl.Add Left$(myVar(I), Count), Left$(myVar(I), Count)
I = I + 1
Loop While Err.Number = 0 And I <= UBound(myVar)
Flag = Err.Number = 0
On Error GoTo 0
I = 0
Set myColl = Nothing
Loop While Not Flag
MinimalLenght = Count
End Function
|
Port the following code from Ruby to Go with equivalent syntax and logic. | require "abbrev"
File.read("daynames.txt").each_line do |line|
next if line.strip.empty?
abbr = line.split.abbrev.invert
puts "Minimum size:
end
| package main
import(
"bufio"
"fmt"
"os"
"strings"
)
func distinctStrings(strs []string) []string {
len := len(strs)
set := make(map[string]bool, len)
distinct := make([]string, 0, len)
for _, str := range strs {
if !set[str] {
distinct = append(distinct, str)
set[str] = true
}
}
return distinct
}
func takeRunes(s string, n int) string {
i := 0
for j := range s {
if i == n {
return s[:j]
}
i++
}
return s
}
func main() {
file, err := os.Open("days_of_week.txt")
if err != nil {
fmt.Println("Unable to open file.")
return
}
defer file.Close()
reader := bufio.NewReader(file)
lineCount := 0
for {
line, err := reader.ReadString('\n')
if err != nil {
return
}
line = strings.TrimSpace(line)
lineCount++
if line == "" {
fmt.Println()
continue
}
days := strings.Fields(line)
daysLen := len(days)
if (len(days) != 7) {
fmt.Println("There aren't 7 days in line", lineCount)
return
}
if len(distinctStrings(days)) != 7 {
fmt.Println(" β ", line)
continue
}
for abbrevLen := 1; ; abbrevLen++ {
abbrevs := make([]string, daysLen)
for i := 0; i < daysLen; i++ {
abbrevs[i] = takeRunes(days[i], abbrevLen)
}
if len(distinctStrings(abbrevs)) == 7 {
fmt.Printf("%2d %s\n", abbrevLen, line)
break
}
}
}
}
|
Change the programming language of this snippet from Ruby to Go without modifying what it does. | require "abbrev"
File.read("daynames.txt").each_line do |line|
next if line.strip.empty?
abbr = line.split.abbrev.invert
puts "Minimum size:
end
| package main
import(
"bufio"
"fmt"
"os"
"strings"
)
func distinctStrings(strs []string) []string {
len := len(strs)
set := make(map[string]bool, len)
distinct := make([]string, 0, len)
for _, str := range strs {
if !set[str] {
distinct = append(distinct, str)
set[str] = true
}
}
return distinct
}
func takeRunes(s string, n int) string {
i := 0
for j := range s {
if i == n {
return s[:j]
}
i++
}
return s
}
func main() {
file, err := os.Open("days_of_week.txt")
if err != nil {
fmt.Println("Unable to open file.")
return
}
defer file.Close()
reader := bufio.NewReader(file)
lineCount := 0
for {
line, err := reader.ReadString('\n')
if err != nil {
return
}
line = strings.TrimSpace(line)
lineCount++
if line == "" {
fmt.Println()
continue
}
days := strings.Fields(line)
daysLen := len(days)
if (len(days) != 7) {
fmt.Println("There aren't 7 days in line", lineCount)
return
}
if len(distinctStrings(days)) != 7 {
fmt.Println(" β ", line)
continue
}
for abbrevLen := 1; ; abbrevLen++ {
abbrevs := make([]string, daysLen)
for i := 0; i < daysLen; i++ {
abbrevs[i] = takeRunes(days[i], abbrevLen)
}
if len(distinctStrings(abbrevs)) == 7 {
fmt.Printf("%2d %s\n", abbrevLen, line)
break
}
}
}
}
|
Produce a functionally identical C code for the snippet given in Scala. |
import java.io.File
val r = Regex("[ ]+")
fun main(args: Array<String>) {
val lines = File("days_of_week.txt").readLines()
for ((i, line) in lines.withIndex()) {
if (line.trim().isEmpty()) {
println()
continue
}
val days = line.trim().split(r)
if (days.size != 7) throw RuntimeException("There aren't 7 days in line ${i + 1}")
if (days.distinct().size < 7) {
println(" β $line")
continue
}
var len = 1
while (true) {
if (days.map { it.take(len) }.distinct().size == 7) {
println("${"%2d".format(len)} $line")
break
}
len++
}
}
}
| #include <stdio.h>
#include <stdlib.h>
#include <string.h>
void process(int lineNum, char buffer[]) {
char days[7][64];
int i = 0, d = 0, j = 0;
while (buffer[i] != 0) {
if (buffer[i] == ' ') {
days[d][j] = '\0';
++d;
j = 0;
} else if (buffer[i] == '\n' || buffer[i] == '\r') {
days[d][j] = '\0';
++d;
break;
} else {
days[d][j] = buffer[i];
++j;
}
if (d >= 7) {
printf("There aren't 7 days in line %d\n", lineNum);
return;
}
++i;
}
if (buffer[i] == '\0') {
days[d][j] = '\0';
++d;
}
if (d < 7) {
printf("There aren't 7 days in line %d\n", lineNum);
return;
} else {
int len = 0;
for (len = 1; len < 64; ++len) {
int d1;
for (d1 = 0; d1 < 7; ++d1) {
int d2;
for (d2 = d1 + 1; d2 < 7; ++d2) {
int unique = 0;
for (i = 0; i < len; ++i) {
if (days[d1][i] != days[d2][i]) {
unique = 1;
break;
}
}
if (!unique) {
goto next_length;
}
}
}
printf("%2d ", len);
for (i = 0; i < 7; ++i) {
printf(" %s", days[i]);
}
printf("\n");
return;
next_length: {}
}
}
printf("Failed to find uniqueness within the bounds.");
}
int main() {
char buffer[1024];
int lineNum = 1, len;
FILE *fp;
fp = fopen("days_of_week.txt", "r");
while (1) {
memset(buffer, 0, sizeof(buffer));
fgets(buffer, sizeof(buffer), fp);
len = strlen(buffer);
if (len == 0 || buffer[len - 1] == '\0') {
break;
}
process(lineNum++, buffer);
}
fclose(fp);
return 0;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.