Instruction
stringlengths
45
106
input_code
stringlengths
1
13.7k
output_code
stringlengths
1
13.7k
Generate a PHP translation of this Perl snippet without changing its computational steps.
sub perf { my $n = shift; my $sum = 0; foreach my $i (1..$n-1) { if ($n % $i == 0) { $sum += $i; } } return $sum == $n; }
function is_perfect($number) { $sum = 0; for($i = 1; $i < $number; $i++) { if($number % $i == 0) $sum += $i; } return $sum == $number; } echo "Perfect numbers from 1 to 33550337:" . PHP_EOL; for($num = 1; $num < 33550337; $num++) { if(is_perfect($num)) echo $num . PHP_EOL; }
Produce a language-to-language conversion: from PowerShell to PHP, same semantics.
Function IsPerfect($n) { $sum=0 for($i=1;$i-lt$n;$i++) { if($n%$i -eq 0) { $sum += $i } } return $sum -eq $n } Returns "True" if the given number is perfect and "False" if it's not.
function is_perfect($number) { $sum = 0; for($i = 1; $i < $number; $i++) { if($number % $i == 0) $sum += $i; } return $sum == $number; } echo "Perfect numbers from 1 to 33550337:" . PHP_EOL; for($num = 1; $num < 33550337; $num++) { if(is_perfect($num)) echo $num . PHP_EOL; }
Please provide an equivalent version of this R code in PHP.
is.perf <- function(n){ if (n==0|n==1) return(FALSE) s <- seq (1,n-1) x <- n %% s m <- data.frame(s,x) out <- with(m, s[x==0]) return(sum(out)==n) } is.perf(28) sapply(c(6,28,496,8128,33550336),is.perf)
function is_perfect($number) { $sum = 0; for($i = 1; $i < $number; $i++) { if($number % $i == 0) $sum += $i; } return $sum == $number; } echo "Perfect numbers from 1 to 33550337:" . PHP_EOL; for($num = 1; $num < 33550337; $num++) { if(is_perfect($num)) echo $num . PHP_EOL; }
Rewrite the snippet below in PHP so it works the same as the original Racket code.
#lang racket (require math) (define (perfect? n) (= (* n 2) (sum (divisors n)))) (filter perfect? (filter even? (range 1e5)))
function is_perfect($number) { $sum = 0; for($i = 1; $i < $number; $i++) { if($number % $i == 0) $sum += $i; } return $sum == $number; } echo "Perfect numbers from 1 to 33550337:" . PHP_EOL; for($num = 1; $num < 33550337; $num++) { if(is_perfect($num)) echo $num . PHP_EOL; }
Convert this COBOL block to PHP, preserving its control flow and logic.
$set REPOSITORY "UPDATE ON" IDENTIFICATION DIVISION. PROGRAM-ID. perfect-main. ENVIRONMENT DIVISION. CONFIGURATION SECTION. REPOSITORY. FUNCTION perfect . DATA DIVISION. WORKING-STORAGE SECTION. 01 i PIC 9(8). PROCEDURE DIVISION. PERFORM VARYING i FROM 2 BY 1 UNTIL 33550337 = i IF FUNCTION perfect(i) = 0 DISPLAY i END-IF END-PERFORM GOBACK . END PROGRAM perfect-main.
function is_perfect($number) { $sum = 0; for($i = 1; $i < $number; $i++) { if($number % $i == 0) $sum += $i; } return $sum == $number; } echo "Perfect numbers from 1 to 33550337:" . PHP_EOL; for($num = 1; $num < 33550337; $num++) { if(is_perfect($num)) echo $num . PHP_EOL; }
Convert this REXX block to PHP, preserving its control flow and logic.
-- first perfect number over 10000 is 33550336...let's not be crazy loop i = 1 to 10000 if perfectNumber(i) then say i "is a perfect number" end ::routine perfectNumber use strict arg n sum = 0 -- the largest possible factor is n % 2, so no point in -- going higher than that loop i = 1 to n % 2 if n // i == 0 then sum += i end return sum = n
function is_perfect($number) { $sum = 0; for($i = 1; $i < $number; $i++) { if($number % $i == 0) $sum += $i; } return $sum == $number; } echo "Perfect numbers from 1 to 33550337:" . PHP_EOL; for($num = 1; $num < 33550337; $num++) { if(is_perfect($num)) echo $num . PHP_EOL; }
Rewrite the snippet below in PHP so it works the same as the original Ruby code.
def perf(n) sum = 0 for i in 1...n sum += i if n % i == 0 end sum == n end
function is_perfect($number) { $sum = 0; for($i = 1; $i < $number; $i++) { if($number % $i == 0) $sum += $i; } return $sum == $number; } echo "Perfect numbers from 1 to 33550337:" . PHP_EOL; for($num = 1; $num < 33550337; $num++) { if(is_perfect($num)) echo $num . PHP_EOL; }
Translate the given Scala code snippet into PHP without altering its behavior.
fun isPerfect(n: Int): Boolean = when { n < 2 -> false n % 2 == 1 -> false else -> { var tot = 1 var q: Int for (i in 2 .. Math.sqrt(n.toDouble()).toInt()) { if (n % i == 0) { tot += i q = n / i if (q > i) tot += q } } n == tot } } fun main(args: Array<String>) { println("The first five perfect numbers are:") for (i in 2 .. 33550336) if (isPerfect(i)) print("$i ") }
function is_perfect($number) { $sum = 0; for($i = 1; $i < $number; $i++) { if($number % $i == 0) $sum += $i; } return $sum == $number; } echo "Perfect numbers from 1 to 33550337:" . PHP_EOL; for($num = 1; $num < 33550337; $num++) { if(is_perfect($num)) echo $num . PHP_EOL; }
Maintain the same structure and functionality when rewriting this code in PHP.
func perfect(n:Int) -> Bool { var sum = 0 for i in 1..<n { if n % i == 0 { sum += i } } return sum == n } for i in 1..<10000 { if perfect(i) { println(i) } }
function is_perfect($number) { $sum = 0; for($i = 1; $i < $number; $i++) { if($number % $i == 0) $sum += $i; } return $sum == $number; } echo "Perfect numbers from 1 to 33550337:" . PHP_EOL; for($num = 1; $num < 33550337; $num++) { if(is_perfect($num)) echo $num . PHP_EOL; }
Generate an equivalent PHP version of this Tcl code.
proc perfect n { set sum 0 for {set i 1} {$i <= $n} {incr i} { if {$n % $i == 0} {incr sum $i} } expr {$sum == 2*$n} }
function is_perfect($number) { $sum = 0; for($i = 1; $i < $number; $i++) { if($number % $i == 0) $sum += $i; } return $sum == $number; } echo "Perfect numbers from 1 to 33550337:" . PHP_EOL; for($num = 1; $num < 33550337; $num++) { if(is_perfect($num)) echo $num . PHP_EOL; }
Produce a functionally identical Rust code for the snippet given in C.
#include "stdio.h" #include "math.h" int perfect(int n) { int max = (int)sqrt((double)n) + 1; int tot = 1; int i; for (i = 2; i < max; i++) if ( (n % i) == 0 ) { tot += i; int q = n / i; if (q > i) tot += q; } return tot == n; } int main() { int n; for (n = 2; n < 33550337; n++) if (perfect(n)) printf("%d\n", n); return 0; }
fn main ( ) { fn factor_sum(n: i32) -> i32 { let mut v = Vec::new(); for x in 1..n-1 { if n%x == 0 { v.push(x); } } let mut sum = v.iter().sum(); return sum; } fn perfect_nums(n: i32) { for x in 2..n { if factor_sum(x) == x { println!("{} is a perfect number.", x); } } } perfect_nums(10000); }
Translate this program into Rust but keep the logic exactly as in C++.
#include <iostream> using namespace std ; int divisor_sum( int number ) { int sum = 0 ; for ( int i = 1 ; i < number ; i++ ) if ( number % i == 0 ) sum += i ; return sum; } int main( ) { cout << "Perfect numbers from 1 to 33550337:\n" ; for ( int num = 1 ; num < 33550337 ; num++ ) { if (divisor_sum(num) == num) cout << num << '\n' ; } return 0 ; }
fn main ( ) { fn factor_sum(n: i32) -> i32 { let mut v = Vec::new(); for x in 1..n-1 { if n%x == 0 { v.push(x); } } let mut sum = v.iter().sum(); return sum; } fn perfect_nums(n: i32) { for x in 2..n { if factor_sum(x) == x { println!("{} is a perfect number.", x); } } } perfect_nums(10000); }
Convert this C# snippet to Rust and keep its semantics consistent.
static void Main(string[] args) { Console.WriteLine("Perfect numbers from 1 to 33550337:"); for (int x = 0; x < 33550337; x++) { if (IsPerfect(x)) Console.WriteLine(x + " is perfect."); } Console.ReadLine(); } static bool IsPerfect(int num) { int sum = 0; for (int i = 1; i < num; i++) { if (num % i == 0) sum += i; } return sum == num ; }
fn main ( ) { fn factor_sum(n: i32) -> i32 { let mut v = Vec::new(); for x in 1..n-1 { if n%x == 0 { v.push(x); } } let mut sum = v.iter().sum(); return sum; } fn perfect_nums(n: i32) { for x in 2..n { if factor_sum(x) == x { println!("{} is a perfect number.", x); } } } perfect_nums(10000); }
Rewrite the snippet below in Python so it works the same as the original Rust code.
fn main ( ) { fn factor_sum(n: i32) -> i32 { let mut v = Vec::new(); for x in 1..n-1 { if n%x == 0 { v.push(x); } } let mut sum = v.iter().sum(); return sum; } fn perfect_nums(n: i32) { for x in 2..n { if factor_sum(x) == x { println!("{} is a perfect number.", x); } } } perfect_nums(10000); }
def perf1(n): sum = 0 for i in range(1, n): if n % i == 0: sum += i return sum == n
Rewrite this program in VB while keeping its functionality equivalent to the Rust version.
fn main ( ) { fn factor_sum(n: i32) -> i32 { let mut v = Vec::new(); for x in 1..n-1 { if n%x == 0 { v.push(x); } } let mut sum = v.iter().sum(); return sum; } fn perfect_nums(n: i32) { for x in 2..n { if factor_sum(x) == x { println!("{} is a perfect number.", x); } } } perfect_nums(10000); }
Private Function Factors(x As Long) As String Application.Volatile Dim i As Long Dim cooresponding_factors As String Factors = 1 corresponding_factors = x For i = 2 To Sqr(x) If x Mod i = 0 Then Factors = Factors & ", " & i If i <> x / i Then corresponding_factors = x / i & ", " & corresponding_factors End If Next i If x <> 1 Then Factors = Factors & ", " & corresponding_factors End Function Private Function is_perfect(n As Long) fs = Split(Factors(n), ", ") Dim f() As Long ReDim f(UBound(fs)) For i = 0 To UBound(fs) f(i) = Val(fs(i)) Next i is_perfect = WorksheetFunction.Sum(f) - n = n End Function Public Sub main() Dim i As Long For i = 2 To 100000 If is_perfect(i) Then Debug.Print i Next i End Sub
Please provide an equivalent version of this Java code in Rust.
public static boolean perf(int n){ int sum= 0; for(int i= 1;i < n;i++){ if(n % i == 0){ sum+= i; } } return sum == n; }
fn main ( ) { fn factor_sum(n: i32) -> i32 { let mut v = Vec::new(); for x in 1..n-1 { if n%x == 0 { v.push(x); } } let mut sum = v.iter().sum(); return sum; } fn perfect_nums(n: i32) { for x in 2..n { if factor_sum(x) == x { println!("{} is a perfect number.", x); } } } perfect_nums(10000); }
Translate this program into Rust but keep the logic exactly as in Go.
package main import "fmt" func computePerfect(n int64) bool { var sum int64 for i := int64(1); i < n; i++ { if n%i == 0 { sum += i } } return sum == n } func isPerfect(n int64) bool { switch n { case 6, 28, 496, 8128, 33550336, 8589869056, 137438691328, 2305843008139952128: return true } return false } func main() { for n := int64(1); ; n++ { if isPerfect(n) != computePerfect(n) { panic("bug") } if n%1e3 == 0 { fmt.Println("tested", n) } } }
fn main ( ) { fn factor_sum(n: i32) -> i32 { let mut v = Vec::new(); for x in 1..n-1 { if n%x == 0 { v.push(x); } } let mut sum = v.iter().sum(); return sum; } fn perfect_nums(n: i32) { for x in 2..n { if factor_sum(x) == x { println!("{} is a perfect number.", x); } } } perfect_nums(10000); }
Ensure the translated C# code behaves exactly like the original Ada snippet.
with Ada.Containers.Indefinite_Vectors; with Ada.Strings.Fixed; with Ada.Strings.Maps; with Ada.Text_IO; procedure Abbreviations is package String_Vectors is new Ada.Containers.Indefinite_Vectors (Index_Type => Positive, Element_Type => String); use Ada.Text_IO, String_Vectors; function Split (Line : String) return Vector is Result : Vector; First : Natural; Last : Natural := Line'First - 1; begin while Last + 1 in Line'Range loop Ada.Strings.Fixed.Find_Token (Line, Ada.Strings.Maps.To_Set (" "), Last + 1, Ada.Strings.Outside, First, Last); exit when Last = 0; Append (Result, Line (First .. Last)); end loop; return Result; end Split; function Abbrev_Length (Items : Vector) return Natural is use type Ada.Containers.Count_Type; Max : Natural := 0; Abbrevs : Vector; begin for Item of Items loop Max := Natural'Max (Max, Item'Length); end loop; for Length in 1 .. Max loop Abbrevs := Empty_Vector; for Item of Items loop declare Last : constant Natural := Natural'Min (Item'Last, Item'First + Length - 1); Abbrev : String renames Item (Item'First .. Last); begin exit when Abbrevs.Contains (Abbrev); Abbrevs.Append (Abbrev); end; end loop; if Abbrevs.Length = Items.Length then return Length; end if; end loop; return 0; end Abbrev_Length; procedure Process (Line : String) is package Natural_IO is new Ada.Text_IO.Integer_IO (Natural); Words : constant Vector := Split (Line); Length : constant Natural := Abbrev_Length (Words); begin Natural_IO.Put (Length, Width => 2); Put (" "); Put_Line (Line); end Process; begin while not End_Of_File loop Process (Get_Line); end loop; end Abbreviations;
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 Ada.
with Ada.Containers.Indefinite_Vectors; with Ada.Strings.Fixed; with Ada.Strings.Maps; with Ada.Text_IO; procedure Abbreviations is package String_Vectors is new Ada.Containers.Indefinite_Vectors (Index_Type => Positive, Element_Type => String); use Ada.Text_IO, String_Vectors; function Split (Line : String) return Vector is Result : Vector; First : Natural; Last : Natural := Line'First - 1; begin while Last + 1 in Line'Range loop Ada.Strings.Fixed.Find_Token (Line, Ada.Strings.Maps.To_Set (" "), Last + 1, Ada.Strings.Outside, First, Last); exit when Last = 0; Append (Result, Line (First .. Last)); end loop; return Result; end Split; function Abbrev_Length (Items : Vector) return Natural is use type Ada.Containers.Count_Type; Max : Natural := 0; Abbrevs : Vector; begin for Item of Items loop Max := Natural'Max (Max, Item'Length); end loop; for Length in 1 .. Max loop Abbrevs := Empty_Vector; for Item of Items loop declare Last : constant Natural := Natural'Min (Item'Last, Item'First + Length - 1); Abbrev : String renames Item (Item'First .. Last); begin exit when Abbrevs.Contains (Abbrev); Abbrevs.Append (Abbrev); end; end loop; if Abbrevs.Length = Items.Length then return Length; end if; end loop; return 0; end Abbrev_Length; procedure Process (Line : String) is package Natural_IO is new Ada.Text_IO.Integer_IO (Natural); Words : constant Vector := Split (Line); Length : constant Natural := Abbrev_Length (Words); begin Natural_IO.Put (Length, Width => 2); Put (" "); Put_Line (Line); end Process; begin while not End_Of_File loop Process (Get_Line); end loop; end Abbreviations;
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 Ada block to C, preserving its control flow and logic.
with Ada.Containers.Indefinite_Vectors; with Ada.Strings.Fixed; with Ada.Strings.Maps; with Ada.Text_IO; procedure Abbreviations is package String_Vectors is new Ada.Containers.Indefinite_Vectors (Index_Type => Positive, Element_Type => String); use Ada.Text_IO, String_Vectors; function Split (Line : String) return Vector is Result : Vector; First : Natural; Last : Natural := Line'First - 1; begin while Last + 1 in Line'Range loop Ada.Strings.Fixed.Find_Token (Line, Ada.Strings.Maps.To_Set (" "), Last + 1, Ada.Strings.Outside, First, Last); exit when Last = 0; Append (Result, Line (First .. Last)); end loop; return Result; end Split; function Abbrev_Length (Items : Vector) return Natural is use type Ada.Containers.Count_Type; Max : Natural := 0; Abbrevs : Vector; begin for Item of Items loop Max := Natural'Max (Max, Item'Length); end loop; for Length in 1 .. Max loop Abbrevs := Empty_Vector; for Item of Items loop declare Last : constant Natural := Natural'Min (Item'Last, Item'First + Length - 1); Abbrev : String renames Item (Item'First .. Last); begin exit when Abbrevs.Contains (Abbrev); Abbrevs.Append (Abbrev); end; end loop; if Abbrevs.Length = Items.Length then return Length; end if; end loop; return 0; end Abbrev_Length; procedure Process (Line : String) is package Natural_IO is new Ada.Text_IO.Integer_IO (Natural); Words : constant Vector := Split (Line); Length : constant Natural := Abbrev_Length (Words); begin Natural_IO.Put (Length, Width => 2); Put (" "); Put_Line (Line); end Process; begin while not End_Of_File loop Process (Get_Line); end loop; end Abbreviations;
#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 Ada snippet to C and keep its semantics consistent.
with Ada.Containers.Indefinite_Vectors; with Ada.Strings.Fixed; with Ada.Strings.Maps; with Ada.Text_IO; procedure Abbreviations is package String_Vectors is new Ada.Containers.Indefinite_Vectors (Index_Type => Positive, Element_Type => String); use Ada.Text_IO, String_Vectors; function Split (Line : String) return Vector is Result : Vector; First : Natural; Last : Natural := Line'First - 1; begin while Last + 1 in Line'Range loop Ada.Strings.Fixed.Find_Token (Line, Ada.Strings.Maps.To_Set (" "), Last + 1, Ada.Strings.Outside, First, Last); exit when Last = 0; Append (Result, Line (First .. Last)); end loop; return Result; end Split; function Abbrev_Length (Items : Vector) return Natural is use type Ada.Containers.Count_Type; Max : Natural := 0; Abbrevs : Vector; begin for Item of Items loop Max := Natural'Max (Max, Item'Length); end loop; for Length in 1 .. Max loop Abbrevs := Empty_Vector; for Item of Items loop declare Last : constant Natural := Natural'Min (Item'Last, Item'First + Length - 1); Abbrev : String renames Item (Item'First .. Last); begin exit when Abbrevs.Contains (Abbrev); Abbrevs.Append (Abbrev); end; end loop; if Abbrevs.Length = Items.Length then return Length; end if; end loop; return 0; end Abbrev_Length; procedure Process (Line : String) is package Natural_IO is new Ada.Text_IO.Integer_IO (Natural); Words : constant Vector := Split (Line); Length : constant Natural := Abbrev_Length (Words); begin Natural_IO.Put (Length, Width => 2); Put (" "); Put_Line (Line); end Process; begin while not End_Of_File loop Process (Get_Line); end loop; end Abbreviations;
#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 functionally identical C++ code for the snippet given in Ada.
with Ada.Containers.Indefinite_Vectors; with Ada.Strings.Fixed; with Ada.Strings.Maps; with Ada.Text_IO; procedure Abbreviations is package String_Vectors is new Ada.Containers.Indefinite_Vectors (Index_Type => Positive, Element_Type => String); use Ada.Text_IO, String_Vectors; function Split (Line : String) return Vector is Result : Vector; First : Natural; Last : Natural := Line'First - 1; begin while Last + 1 in Line'Range loop Ada.Strings.Fixed.Find_Token (Line, Ada.Strings.Maps.To_Set (" "), Last + 1, Ada.Strings.Outside, First, Last); exit when Last = 0; Append (Result, Line (First .. Last)); end loop; return Result; end Split; function Abbrev_Length (Items : Vector) return Natural is use type Ada.Containers.Count_Type; Max : Natural := 0; Abbrevs : Vector; begin for Item of Items loop Max := Natural'Max (Max, Item'Length); end loop; for Length in 1 .. Max loop Abbrevs := Empty_Vector; for Item of Items loop declare Last : constant Natural := Natural'Min (Item'Last, Item'First + Length - 1); Abbrev : String renames Item (Item'First .. Last); begin exit when Abbrevs.Contains (Abbrev); Abbrevs.Append (Abbrev); end; end loop; if Abbrevs.Length = Items.Length then return Length; end if; end loop; return 0; end Abbrev_Length; procedure Process (Line : String) is package Natural_IO is new Ada.Text_IO.Integer_IO (Natural); Words : constant Vector := Split (Line); Length : constant Natural := Abbrev_Length (Words); begin Natural_IO.Put (Length, Width => 2); Put (" "); Put_Line (Line); end Process; begin while not End_Of_File loop Process (Get_Line); end loop; end Abbreviations;
#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 Ada code in C++.
with Ada.Containers.Indefinite_Vectors; with Ada.Strings.Fixed; with Ada.Strings.Maps; with Ada.Text_IO; procedure Abbreviations is package String_Vectors is new Ada.Containers.Indefinite_Vectors (Index_Type => Positive, Element_Type => String); use Ada.Text_IO, String_Vectors; function Split (Line : String) return Vector is Result : Vector; First : Natural; Last : Natural := Line'First - 1; begin while Last + 1 in Line'Range loop Ada.Strings.Fixed.Find_Token (Line, Ada.Strings.Maps.To_Set (" "), Last + 1, Ada.Strings.Outside, First, Last); exit when Last = 0; Append (Result, Line (First .. Last)); end loop; return Result; end Split; function Abbrev_Length (Items : Vector) return Natural is use type Ada.Containers.Count_Type; Max : Natural := 0; Abbrevs : Vector; begin for Item of Items loop Max := Natural'Max (Max, Item'Length); end loop; for Length in 1 .. Max loop Abbrevs := Empty_Vector; for Item of Items loop declare Last : constant Natural := Natural'Min (Item'Last, Item'First + Length - 1); Abbrev : String renames Item (Item'First .. Last); begin exit when Abbrevs.Contains (Abbrev); Abbrevs.Append (Abbrev); end; end loop; if Abbrevs.Length = Items.Length then return Length; end if; end loop; return 0; end Abbrev_Length; procedure Process (Line : String) is package Natural_IO is new Ada.Text_IO.Integer_IO (Natural); Words : constant Vector := Split (Line); Length : constant Natural := Abbrev_Length (Words); begin Natural_IO.Put (Length, Width => 2); Put (" "); Put_Line (Line); end Process; begin while not End_Of_File loop Process (Get_Line); end loop; end Abbreviations;
#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; }
Port the following code from Ada to Go with equivalent syntax and logic.
with Ada.Containers.Indefinite_Vectors; with Ada.Strings.Fixed; with Ada.Strings.Maps; with Ada.Text_IO; procedure Abbreviations is package String_Vectors is new Ada.Containers.Indefinite_Vectors (Index_Type => Positive, Element_Type => String); use Ada.Text_IO, String_Vectors; function Split (Line : String) return Vector is Result : Vector; First : Natural; Last : Natural := Line'First - 1; begin while Last + 1 in Line'Range loop Ada.Strings.Fixed.Find_Token (Line, Ada.Strings.Maps.To_Set (" "), Last + 1, Ada.Strings.Outside, First, Last); exit when Last = 0; Append (Result, Line (First .. Last)); end loop; return Result; end Split; function Abbrev_Length (Items : Vector) return Natural is use type Ada.Containers.Count_Type; Max : Natural := 0; Abbrevs : Vector; begin for Item of Items loop Max := Natural'Max (Max, Item'Length); end loop; for Length in 1 .. Max loop Abbrevs := Empty_Vector; for Item of Items loop declare Last : constant Natural := Natural'Min (Item'Last, Item'First + Length - 1); Abbrev : String renames Item (Item'First .. Last); begin exit when Abbrevs.Contains (Abbrev); Abbrevs.Append (Abbrev); end; end loop; if Abbrevs.Length = Items.Length then return Length; end if; end loop; return 0; end Abbrev_Length; procedure Process (Line : String) is package Natural_IO is new Ada.Text_IO.Integer_IO (Natural); Words : constant Vector := Split (Line); Length : constant Natural := Abbrev_Length (Words); begin Natural_IO.Put (Length, Width => 2); Put (" "); Put_Line (Line); end Process; begin while not End_Of_File loop Process (Get_Line); end loop; end Abbreviations;
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 Go so it works the same as the original Ada code.
with Ada.Containers.Indefinite_Vectors; with Ada.Strings.Fixed; with Ada.Strings.Maps; with Ada.Text_IO; procedure Abbreviations is package String_Vectors is new Ada.Containers.Indefinite_Vectors (Index_Type => Positive, Element_Type => String); use Ada.Text_IO, String_Vectors; function Split (Line : String) return Vector is Result : Vector; First : Natural; Last : Natural := Line'First - 1; begin while Last + 1 in Line'Range loop Ada.Strings.Fixed.Find_Token (Line, Ada.Strings.Maps.To_Set (" "), Last + 1, Ada.Strings.Outside, First, Last); exit when Last = 0; Append (Result, Line (First .. Last)); end loop; return Result; end Split; function Abbrev_Length (Items : Vector) return Natural is use type Ada.Containers.Count_Type; Max : Natural := 0; Abbrevs : Vector; begin for Item of Items loop Max := Natural'Max (Max, Item'Length); end loop; for Length in 1 .. Max loop Abbrevs := Empty_Vector; for Item of Items loop declare Last : constant Natural := Natural'Min (Item'Last, Item'First + Length - 1); Abbrev : String renames Item (Item'First .. Last); begin exit when Abbrevs.Contains (Abbrev); Abbrevs.Append (Abbrev); end; end loop; if Abbrevs.Length = Items.Length then return Length; end if; end loop; return 0; end Abbrev_Length; procedure Process (Line : String) is package Natural_IO is new Ada.Text_IO.Integer_IO (Natural); Words : constant Vector := Split (Line); Length : constant Natural := Abbrev_Length (Words); begin Natural_IO.Put (Length, Width => 2); Put (" "); Put_Line (Line); end Process; begin while not End_Of_File loop Process (Get_Line); end loop; end Abbreviations;
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 code in Java as shown below in Ada.
with Ada.Containers.Indefinite_Vectors; with Ada.Strings.Fixed; with Ada.Strings.Maps; with Ada.Text_IO; procedure Abbreviations is package String_Vectors is new Ada.Containers.Indefinite_Vectors (Index_Type => Positive, Element_Type => String); use Ada.Text_IO, String_Vectors; function Split (Line : String) return Vector is Result : Vector; First : Natural; Last : Natural := Line'First - 1; begin while Last + 1 in Line'Range loop Ada.Strings.Fixed.Find_Token (Line, Ada.Strings.Maps.To_Set (" "), Last + 1, Ada.Strings.Outside, First, Last); exit when Last = 0; Append (Result, Line (First .. Last)); end loop; return Result; end Split; function Abbrev_Length (Items : Vector) return Natural is use type Ada.Containers.Count_Type; Max : Natural := 0; Abbrevs : Vector; begin for Item of Items loop Max := Natural'Max (Max, Item'Length); end loop; for Length in 1 .. Max loop Abbrevs := Empty_Vector; for Item of Items loop declare Last : constant Natural := Natural'Min (Item'Last, Item'First + Length - 1); Abbrev : String renames Item (Item'First .. Last); begin exit when Abbrevs.Contains (Abbrev); Abbrevs.Append (Abbrev); end; end loop; if Abbrevs.Length = Items.Length then return Length; end if; end loop; return 0; end Abbrev_Length; procedure Process (Line : String) is package Natural_IO is new Ada.Text_IO.Integer_IO (Natural); Words : constant Vector := Split (Line); Length : constant Natural := Abbrev_Length (Words); begin Natural_IO.Put (Length, Width => 2); Put (" "); Put_Line (Line); end Process; begin while not End_Of_File loop Process (Get_Line); end loop; end Abbreviations;
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++; } } } }
Keep all operations the same but rewrite the snippet in Java.
with Ada.Containers.Indefinite_Vectors; with Ada.Strings.Fixed; with Ada.Strings.Maps; with Ada.Text_IO; procedure Abbreviations is package String_Vectors is new Ada.Containers.Indefinite_Vectors (Index_Type => Positive, Element_Type => String); use Ada.Text_IO, String_Vectors; function Split (Line : String) return Vector is Result : Vector; First : Natural; Last : Natural := Line'First - 1; begin while Last + 1 in Line'Range loop Ada.Strings.Fixed.Find_Token (Line, Ada.Strings.Maps.To_Set (" "), Last + 1, Ada.Strings.Outside, First, Last); exit when Last = 0; Append (Result, Line (First .. Last)); end loop; return Result; end Split; function Abbrev_Length (Items : Vector) return Natural is use type Ada.Containers.Count_Type; Max : Natural := 0; Abbrevs : Vector; begin for Item of Items loop Max := Natural'Max (Max, Item'Length); end loop; for Length in 1 .. Max loop Abbrevs := Empty_Vector; for Item of Items loop declare Last : constant Natural := Natural'Min (Item'Last, Item'First + Length - 1); Abbrev : String renames Item (Item'First .. Last); begin exit when Abbrevs.Contains (Abbrev); Abbrevs.Append (Abbrev); end; end loop; if Abbrevs.Length = Items.Length then return Length; end if; end loop; return 0; end Abbrev_Length; procedure Process (Line : String) is package Natural_IO is new Ada.Text_IO.Integer_IO (Natural); Words : constant Vector := Split (Line); Length : constant Natural := Abbrev_Length (Words); begin Natural_IO.Put (Length, Width => 2); Put (" "); Put_Line (Line); end Process; begin while not End_Of_File loop Process (Get_Line); end loop; end Abbreviations;
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 Ada snippet without changing its computational steps.
with Ada.Containers.Indefinite_Vectors; with Ada.Strings.Fixed; with Ada.Strings.Maps; with Ada.Text_IO; procedure Abbreviations is package String_Vectors is new Ada.Containers.Indefinite_Vectors (Index_Type => Positive, Element_Type => String); use Ada.Text_IO, String_Vectors; function Split (Line : String) return Vector is Result : Vector; First : Natural; Last : Natural := Line'First - 1; begin while Last + 1 in Line'Range loop Ada.Strings.Fixed.Find_Token (Line, Ada.Strings.Maps.To_Set (" "), Last + 1, Ada.Strings.Outside, First, Last); exit when Last = 0; Append (Result, Line (First .. Last)); end loop; return Result; end Split; function Abbrev_Length (Items : Vector) return Natural is use type Ada.Containers.Count_Type; Max : Natural := 0; Abbrevs : Vector; begin for Item of Items loop Max := Natural'Max (Max, Item'Length); end loop; for Length in 1 .. Max loop Abbrevs := Empty_Vector; for Item of Items loop declare Last : constant Natural := Natural'Min (Item'Last, Item'First + Length - 1); Abbrev : String renames Item (Item'First .. Last); begin exit when Abbrevs.Contains (Abbrev); Abbrevs.Append (Abbrev); end; end loop; if Abbrevs.Length = Items.Length then return Length; end if; end loop; return 0; end Abbrev_Length; procedure Process (Line : String) is package Natural_IO is new Ada.Text_IO.Integer_IO (Natural); Words : constant Vector := Split (Line); Length : constant Natural := Abbrev_Length (Words); begin Natural_IO.Put (Length, Width => 2); Put (" "); Put_Line (Line); end Process; begin while not End_Of_File loop Process (Get_Line); end loop; end Abbreviations;
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 Ada to Python.
with Ada.Containers.Indefinite_Vectors; with Ada.Strings.Fixed; with Ada.Strings.Maps; with Ada.Text_IO; procedure Abbreviations is package String_Vectors is new Ada.Containers.Indefinite_Vectors (Index_Type => Positive, Element_Type => String); use Ada.Text_IO, String_Vectors; function Split (Line : String) return Vector is Result : Vector; First : Natural; Last : Natural := Line'First - 1; begin while Last + 1 in Line'Range loop Ada.Strings.Fixed.Find_Token (Line, Ada.Strings.Maps.To_Set (" "), Last + 1, Ada.Strings.Outside, First, Last); exit when Last = 0; Append (Result, Line (First .. Last)); end loop; return Result; end Split; function Abbrev_Length (Items : Vector) return Natural is use type Ada.Containers.Count_Type; Max : Natural := 0; Abbrevs : Vector; begin for Item of Items loop Max := Natural'Max (Max, Item'Length); end loop; for Length in 1 .. Max loop Abbrevs := Empty_Vector; for Item of Items loop declare Last : constant Natural := Natural'Min (Item'Last, Item'First + Length - 1); Abbrev : String renames Item (Item'First .. Last); begin exit when Abbrevs.Contains (Abbrev); Abbrevs.Append (Abbrev); end; end loop; if Abbrevs.Length = Items.Length then return Length; end if; end loop; return 0; end Abbrev_Length; procedure Process (Line : String) is package Natural_IO is new Ada.Text_IO.Integer_IO (Natural); Words : constant Vector := Split (Line); Length : constant Natural := Abbrev_Length (Words); begin Natural_IO.Put (Length, Width => 2); Put (" "); Put_Line (Line); end Process; begin while not End_Of_File loop Process (Get_Line); end loop; end Abbreviations;
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 Ada block to VB, preserving its control flow and logic.
with Ada.Containers.Indefinite_Vectors; with Ada.Strings.Fixed; with Ada.Strings.Maps; with Ada.Text_IO; procedure Abbreviations is package String_Vectors is new Ada.Containers.Indefinite_Vectors (Index_Type => Positive, Element_Type => String); use Ada.Text_IO, String_Vectors; function Split (Line : String) return Vector is Result : Vector; First : Natural; Last : Natural := Line'First - 1; begin while Last + 1 in Line'Range loop Ada.Strings.Fixed.Find_Token (Line, Ada.Strings.Maps.To_Set (" "), Last + 1, Ada.Strings.Outside, First, Last); exit when Last = 0; Append (Result, Line (First .. Last)); end loop; return Result; end Split; function Abbrev_Length (Items : Vector) return Natural is use type Ada.Containers.Count_Type; Max : Natural := 0; Abbrevs : Vector; begin for Item of Items loop Max := Natural'Max (Max, Item'Length); end loop; for Length in 1 .. Max loop Abbrevs := Empty_Vector; for Item of Items loop declare Last : constant Natural := Natural'Min (Item'Last, Item'First + Length - 1); Abbrev : String renames Item (Item'First .. Last); begin exit when Abbrevs.Contains (Abbrev); Abbrevs.Append (Abbrev); end; end loop; if Abbrevs.Length = Items.Length then return Length; end if; end loop; return 0; end Abbrev_Length; procedure Process (Line : String) is package Natural_IO is new Ada.Text_IO.Integer_IO (Natural); Words : constant Vector := Split (Line); Length : constant Natural := Abbrev_Length (Words); begin Natural_IO.Put (Length, Width => 2); Put (" "); Put_Line (Line); end Process; begin while not End_Of_File loop Process (Get_Line); end loop; end Abbreviations;
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
Rewrite this program in VB while keeping its functionality equivalent to the Ada version.
with Ada.Containers.Indefinite_Vectors; with Ada.Strings.Fixed; with Ada.Strings.Maps; with Ada.Text_IO; procedure Abbreviations is package String_Vectors is new Ada.Containers.Indefinite_Vectors (Index_Type => Positive, Element_Type => String); use Ada.Text_IO, String_Vectors; function Split (Line : String) return Vector is Result : Vector; First : Natural; Last : Natural := Line'First - 1; begin while Last + 1 in Line'Range loop Ada.Strings.Fixed.Find_Token (Line, Ada.Strings.Maps.To_Set (" "), Last + 1, Ada.Strings.Outside, First, Last); exit when Last = 0; Append (Result, Line (First .. Last)); end loop; return Result; end Split; function Abbrev_Length (Items : Vector) return Natural is use type Ada.Containers.Count_Type; Max : Natural := 0; Abbrevs : Vector; begin for Item of Items loop Max := Natural'Max (Max, Item'Length); end loop; for Length in 1 .. Max loop Abbrevs := Empty_Vector; for Item of Items loop declare Last : constant Natural := Natural'Min (Item'Last, Item'First + Length - 1); Abbrev : String renames Item (Item'First .. Last); begin exit when Abbrevs.Contains (Abbrev); Abbrevs.Append (Abbrev); end; end loop; if Abbrevs.Length = Items.Length then return Length; end if; end loop; return 0; end Abbrev_Length; procedure Process (Line : String) is package Natural_IO is new Ada.Text_IO.Integer_IO (Natural); Words : constant Vector := Split (Line); Length : constant Natural := Abbrev_Length (Words); begin Natural_IO.Put (Length, Width => 2); Put (" "); Put_Line (Line); end Process; begin while not End_Of_File loop Process (Get_Line); end loop; end Abbreviations;
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 language-to-language conversion: from AutoHotKey to C, same semantics.
AutoAbbreviations(line){ len := prev := 0 Days := StrSplit(line, " ") loop % StrLen(Days.1) { obj := [] for j, day in Days { abb := SubStr(day, 1, len) obj[abb] := (obj[abb] ? obj[abb] : 0) + 1 if (obj[abb] > 1) { len++ break } } if (prev = len) break prev := len } return 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; }
Rewrite this program in C while keeping its functionality equivalent to the AutoHotKey version.
AutoAbbreviations(line){ len := prev := 0 Days := StrSplit(line, " ") loop % StrLen(Days.1) { obj := [] for j, day in Days { abb := SubStr(day, 1, len) obj[abb] := (obj[abb] ? obj[abb] : 0) + 1 if (obj[abb] > 1) { len++ break } } if (prev = len) break prev := len } return 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; }
Convert this AutoHotKey block to C#, preserving its control flow and logic.
AutoAbbreviations(line){ len := prev := 0 Days := StrSplit(line, " ") loop % StrLen(Days.1) { obj := [] for j, day in Days { abb := SubStr(day, 1, len) obj[abb] := (obj[abb] ? obj[abb] : 0) + 1 if (obj[abb] > 1) { len++ break } } if (prev = len) break prev := len } return len }
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 AutoHotKey block to C#, preserving its control flow and logic.
AutoAbbreviations(line){ len := prev := 0 Days := StrSplit(line, " ") loop % StrLen(Days.1) { obj := [] for j, day in Days { abb := SubStr(day, 1, len) obj[abb] := (obj[abb] ? obj[abb] : 0) + 1 if (obj[abb] > 1) { len++ break } } if (prev = len) break prev := len } return len }
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 AutoHotKey implementation into C++, maintaining the same output and logic.
AutoAbbreviations(line){ len := prev := 0 Days := StrSplit(line, " ") loop % StrLen(Days.1) { obj := [] for j, day in Days { abb := SubStr(day, 1, len) obj[abb] := (obj[abb] ? obj[abb] : 0) + 1 if (obj[abb] > 1) { len++ break } } if (prev = len) break prev := len } return len }
#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; }
Keep all operations the same but rewrite the snippet in C++.
AutoAbbreviations(line){ len := prev := 0 Days := StrSplit(line, " ") loop % StrLen(Days.1) { obj := [] for j, day in Days { abb := SubStr(day, 1, len) obj[abb] := (obj[abb] ? obj[abb] : 0) + 1 if (obj[abb] > 1) { len++ break } } if (prev = len) break prev := len } return len }
#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; }
Translate this program into Java but keep the logic exactly as in AutoHotKey.
AutoAbbreviations(line){ len := prev := 0 Days := StrSplit(line, " ") loop % StrLen(Days.1) { obj := [] for j, day in Days { abb := SubStr(day, 1, len) obj[abb] := (obj[abb] ? obj[abb] : 0) + 1 if (obj[abb] > 1) { len++ break } } if (prev = len) break prev := len } return len }
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++; } } } }
Produce a functionally identical Java code for the snippet given in AutoHotKey.
AutoAbbreviations(line){ len := prev := 0 Days := StrSplit(line, " ") loop % StrLen(Days.1) { obj := [] for j, day in Days { abb := SubStr(day, 1, len) obj[abb] := (obj[abb] ? obj[abb] : 0) + 1 if (obj[abb] > 1) { len++ break } } if (prev = len) break prev := len } return len }
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 AutoHotKey implementation into Python, maintaining the same output and logic.
AutoAbbreviations(line){ len := prev := 0 Days := StrSplit(line, " ") loop % StrLen(Days.1) { obj := [] for j, day in Days { abb := SubStr(day, 1, len) obj[abb] := (obj[abb] ? obj[abb] : 0) + 1 if (obj[abb] > 1) { len++ break } } if (prev = len) break prev := len } return len }
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 AutoHotKey to Python.
AutoAbbreviations(line){ len := prev := 0 Days := StrSplit(line, " ") loop % StrLen(Days.1) { obj := [] for j, day in Days { abb := SubStr(day, 1, len) obj[abb] := (obj[abb] ? obj[abb] : 0) + 1 if (obj[abb] > 1) { len++ break } } if (prev = len) break prev := len } return len }
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 AutoHotKey.
AutoAbbreviations(line){ len := prev := 0 Days := StrSplit(line, " ") loop % StrLen(Days.1) { obj := [] for j, day in Days { abb := SubStr(day, 1, len) obj[abb] := (obj[abb] ? obj[abb] : 0) + 1 if (obj[abb] > 1) { len++ break } } if (prev = len) break prev := len } return len }
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
Translate the given AutoHotKey code snippet into VB without altering its behavior.
AutoAbbreviations(line){ len := prev := 0 Days := StrSplit(line, " ") loop % StrLen(Days.1) { obj := [] for j, day in Days { abb := SubStr(day, 1, len) obj[abb] := (obj[abb] ? obj[abb] : 0) + 1 if (obj[abb] > 1) { len++ break } } if (prev = len) break prev := len } return len }
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 AutoHotKey.
AutoAbbreviations(line){ len := prev := 0 Days := StrSplit(line, " ") loop % StrLen(Days.1) { obj := [] for j, day in Days { abb := SubStr(day, 1, len) obj[abb] := (obj[abb] ? obj[abb] : 0) + 1 if (obj[abb] > 1) { len++ break } } if (prev = len) break prev := len } return len }
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 this program in Go while keeping its functionality equivalent to the AutoHotKey version.
AutoAbbreviations(line){ len := prev := 0 Days := StrSplit(line, " ") loop % StrLen(Days.1) { obj := [] for j, day in Days { abb := SubStr(day, 1, len) obj[abb] := (obj[abb] ? obj[abb] : 0) + 1 if (obj[abb] > 1) { len++ break } } if (prev = len) break prev := len } return len }
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 code in C as shown below in AWK.
{ dow_arr[NR] = $0 } END { for (i=1; i<=NR; i++) { if (split(dow_arr[i],arr1,FS) != 7) { printf("NG %s\n",dow_arr[i]) continue } col_width = 0 for (j=1; j<=7; j++) { col_width = max(col_width,length(arr1[j])) } for (col=1; col<=col_width; col++) { delete arr2 for (j=1; j<=7; j++) { arr2[toupper(substr(arr1[j],1,col))] } if (length(arr2) == 7) { break } if (col >= col_width) { col = "NG" break } } printf("%2s %s\n",col,dow_arr[i]) } exit(0) } function max(x,y) { return((x > y) ? x : y) }
#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; }
Can you help me rewrite this code in C instead of AWK, keeping it the same logically?
{ dow_arr[NR] = $0 } END { for (i=1; i<=NR; i++) { if (split(dow_arr[i],arr1,FS) != 7) { printf("NG %s\n",dow_arr[i]) continue } col_width = 0 for (j=1; j<=7; j++) { col_width = max(col_width,length(arr1[j])) } for (col=1; col<=col_width; col++) { delete arr2 for (j=1; j<=7; j++) { arr2[toupper(substr(arr1[j],1,col))] } if (length(arr2) == 7) { break } if (col >= col_width) { col = "NG" break } } printf("%2s %s\n",col,dow_arr[i]) } exit(0) } function max(x,y) { return((x > y) ? x : y) }
#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 AWK code snippet into C# without altering its behavior.
{ dow_arr[NR] = $0 } END { for (i=1; i<=NR; i++) { if (split(dow_arr[i],arr1,FS) != 7) { printf("NG %s\n",dow_arr[i]) continue } col_width = 0 for (j=1; j<=7; j++) { col_width = max(col_width,length(arr1[j])) } for (col=1; col<=col_width; col++) { delete arr2 for (j=1; j<=7; j++) { arr2[toupper(substr(arr1[j],1,col))] } if (length(arr2) == 7) { break } if (col >= col_width) { col = "NG" break } } printf("%2s %s\n",col,dow_arr[i]) } exit(0) } function max(x,y) { return((x > y) ? x : y) }
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++; } } } } } }
Translate this program into C# but keep the logic exactly as in AWK.
{ dow_arr[NR] = $0 } END { for (i=1; i<=NR; i++) { if (split(dow_arr[i],arr1,FS) != 7) { printf("NG %s\n",dow_arr[i]) continue } col_width = 0 for (j=1; j<=7; j++) { col_width = max(col_width,length(arr1[j])) } for (col=1; col<=col_width; col++) { delete arr2 for (j=1; j<=7; j++) { arr2[toupper(substr(arr1[j],1,col))] } if (length(arr2) == 7) { break } if (col >= col_width) { col = "NG" break } } printf("%2s %s\n",col,dow_arr[i]) } exit(0) } function max(x,y) { return((x > y) ? x : y) }
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++; } } } } } }
Translate this program into C++ but keep the logic exactly as in AWK.
{ dow_arr[NR] = $0 } END { for (i=1; i<=NR; i++) { if (split(dow_arr[i],arr1,FS) != 7) { printf("NG %s\n",dow_arr[i]) continue } col_width = 0 for (j=1; j<=7; j++) { col_width = max(col_width,length(arr1[j])) } for (col=1; col<=col_width; col++) { delete arr2 for (j=1; j<=7; j++) { arr2[toupper(substr(arr1[j],1,col))] } if (length(arr2) == 7) { break } if (col >= col_width) { col = "NG" break } } printf("%2s %s\n",col,dow_arr[i]) } exit(0) } function max(x,y) { return((x > y) ? x : y) }
#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; }
Preserve the algorithm and functionality while converting the code from AWK to C++.
{ dow_arr[NR] = $0 } END { for (i=1; i<=NR; i++) { if (split(dow_arr[i],arr1,FS) != 7) { printf("NG %s\n",dow_arr[i]) continue } col_width = 0 for (j=1; j<=7; j++) { col_width = max(col_width,length(arr1[j])) } for (col=1; col<=col_width; col++) { delete arr2 for (j=1; j<=7; j++) { arr2[toupper(substr(arr1[j],1,col))] } if (length(arr2) == 7) { break } if (col >= col_width) { col = "NG" break } } printf("%2s %s\n",col,dow_arr[i]) } exit(0) } function max(x,y) { return((x > y) ? x : y) }
#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; }
Write a version of this AWK function in Java with identical behavior.
{ dow_arr[NR] = $0 } END { for (i=1; i<=NR; i++) { if (split(dow_arr[i],arr1,FS) != 7) { printf("NG %s\n",dow_arr[i]) continue } col_width = 0 for (j=1; j<=7; j++) { col_width = max(col_width,length(arr1[j])) } for (col=1; col<=col_width; col++) { delete arr2 for (j=1; j<=7; j++) { arr2[toupper(substr(arr1[j],1,col))] } if (length(arr2) == 7) { break } if (col >= col_width) { col = "NG" break } } printf("%2s %s\n",col,dow_arr[i]) } exit(0) } function max(x,y) { return((x > y) ? x : y) }
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 AWK to Java.
{ dow_arr[NR] = $0 } END { for (i=1; i<=NR; i++) { if (split(dow_arr[i],arr1,FS) != 7) { printf("NG %s\n",dow_arr[i]) continue } col_width = 0 for (j=1; j<=7; j++) { col_width = max(col_width,length(arr1[j])) } for (col=1; col<=col_width; col++) { delete arr2 for (j=1; j<=7; j++) { arr2[toupper(substr(arr1[j],1,col))] } if (length(arr2) == 7) { break } if (col >= col_width) { col = "NG" break } } printf("%2s %s\n",col,dow_arr[i]) } exit(0) } function max(x,y) { return((x > y) ? x : y) }
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 this program into Python but keep the logic exactly as in AWK.
{ dow_arr[NR] = $0 } END { for (i=1; i<=NR; i++) { if (split(dow_arr[i],arr1,FS) != 7) { printf("NG %s\n",dow_arr[i]) continue } col_width = 0 for (j=1; j<=7; j++) { col_width = max(col_width,length(arr1[j])) } for (col=1; col<=col_width; col++) { delete arr2 for (j=1; j<=7; j++) { arr2[toupper(substr(arr1[j],1,col))] } if (length(arr2) == 7) { break } if (col >= col_width) { col = "NG" break } } printf("%2s %s\n",col,dow_arr[i]) } exit(0) } function max(x,y) { return((x > y) ? x : y) }
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 AWK snippet to Python and keep its semantics consistent.
{ dow_arr[NR] = $0 } END { for (i=1; i<=NR; i++) { if (split(dow_arr[i],arr1,FS) != 7) { printf("NG %s\n",dow_arr[i]) continue } col_width = 0 for (j=1; j<=7; j++) { col_width = max(col_width,length(arr1[j])) } for (col=1; col<=col_width; col++) { delete arr2 for (j=1; j<=7; j++) { arr2[toupper(substr(arr1[j],1,col))] } if (length(arr2) == 7) { break } if (col >= col_width) { col = "NG" break } } printf("%2s %s\n",col,dow_arr[i]) } exit(0) } function max(x,y) { return((x > y) ? x : y) }
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 AWK snippet without changing its computational steps.
{ dow_arr[NR] = $0 } END { for (i=1; i<=NR; i++) { if (split(dow_arr[i],arr1,FS) != 7) { printf("NG %s\n",dow_arr[i]) continue } col_width = 0 for (j=1; j<=7; j++) { col_width = max(col_width,length(arr1[j])) } for (col=1; col<=col_width; col++) { delete arr2 for (j=1; j<=7; j++) { arr2[toupper(substr(arr1[j],1,col))] } if (length(arr2) == 7) { break } if (col >= col_width) { col = "NG" break } } printf("%2s %s\n",col,dow_arr[i]) } exit(0) } function max(x,y) { return((x > y) ? x : y) }
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 AWK code into VB without altering its purpose.
{ dow_arr[NR] = $0 } END { for (i=1; i<=NR; i++) { if (split(dow_arr[i],arr1,FS) != 7) { printf("NG %s\n",dow_arr[i]) continue } col_width = 0 for (j=1; j<=7; j++) { col_width = max(col_width,length(arr1[j])) } for (col=1; col<=col_width; col++) { delete arr2 for (j=1; j<=7; j++) { arr2[toupper(substr(arr1[j],1,col))] } if (length(arr2) == 7) { break } if (col >= col_width) { col = "NG" break } } printf("%2s %s\n",col,dow_arr[i]) } exit(0) } function max(x,y) { return((x > y) ? x : y) }
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
Rewrite this program in Go while keeping its functionality equivalent to the AWK version.
{ dow_arr[NR] = $0 } END { for (i=1; i<=NR; i++) { if (split(dow_arr[i],arr1,FS) != 7) { printf("NG %s\n",dow_arr[i]) continue } col_width = 0 for (j=1; j<=7; j++) { col_width = max(col_width,length(arr1[j])) } for (col=1; col<=col_width; col++) { delete arr2 for (j=1; j<=7; j++) { arr2[toupper(substr(arr1[j],1,col))] } if (length(arr2) == 7) { break } if (col >= col_width) { col = "NG" break } } printf("%2s %s\n",col,dow_arr[i]) } exit(0) } function max(x,y) { return((x > y) ? x : y) }
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 AWK to Go with equivalent syntax and logic.
{ dow_arr[NR] = $0 } END { for (i=1; i<=NR; i++) { if (split(dow_arr[i],arr1,FS) != 7) { printf("NG %s\n",dow_arr[i]) continue } col_width = 0 for (j=1; j<=7; j++) { col_width = max(col_width,length(arr1[j])) } for (col=1; col<=col_width; col++) { delete arr2 for (j=1; j<=7; j++) { arr2[toupper(substr(arr1[j],1,col))] } if (length(arr2) == 7) { break } if (col >= col_width) { col = "NG" break } } printf("%2s %s\n",col,dow_arr[i]) } exit(0) } function max(x,y) { return((x > y) ? x : y) }
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 } } } }
Ensure the translated C code behaves exactly like the original Common_Lisp snippet.
(defun max-mismatch (list) (if (cdr list) (max (apply #'max (mapcar #'(lambda (w2) (mismatch (car list) w2)) (cdr list))) (max-mismatch (cdr list))) 0 )) (with-open-file (f "days-of-the-week.txt" :direction :input) (do* ((row (read-line f nil nil) (read-line f nil nil))) ((null row) t) (format t "~d ~a~%" (1+ (max-mismatch (SPLIT-SEQUENCE:split-sequence #\Space row))) row) ))
#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 Common_Lisp implementation into C, maintaining the same output and logic.
(defun max-mismatch (list) (if (cdr list) (max (apply #'max (mapcar #'(lambda (w2) (mismatch (car list) w2)) (cdr list))) (max-mismatch (cdr list))) 0 )) (with-open-file (f "days-of-the-week.txt" :direction :input) (do* ((row (read-line f nil nil) (read-line f nil nil))) ((null row) t) (format t "~d ~a~%" (1+ (max-mismatch (SPLIT-SEQUENCE:split-sequence #\Space row))) row) ))
#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; }
Can you help me rewrite this code in C# instead of Common_Lisp, keeping it the same logically?
(defun max-mismatch (list) (if (cdr list) (max (apply #'max (mapcar #'(lambda (w2) (mismatch (car list) w2)) (cdr list))) (max-mismatch (cdr list))) 0 )) (with-open-file (f "days-of-the-week.txt" :direction :input) (do* ((row (read-line f nil nil) (read-line f nil nil))) ((null row) t) (format t "~d ~a~%" (1+ (max-mismatch (SPLIT-SEQUENCE:split-sequence #\Space row))) row) ))
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++; } } } } } }
Preserve the algorithm and functionality while converting the code from Common_Lisp to C#.
(defun max-mismatch (list) (if (cdr list) (max (apply #'max (mapcar #'(lambda (w2) (mismatch (car list) w2)) (cdr list))) (max-mismatch (cdr list))) 0 )) (with-open-file (f "days-of-the-week.txt" :direction :input) (do* ((row (read-line f nil nil) (read-line f nil nil))) ((null row) t) (format t "~d ~a~%" (1+ (max-mismatch (SPLIT-SEQUENCE:split-sequence #\Space row))) row) ))
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 Common_Lisp code into C++ without altering its purpose.
(defun max-mismatch (list) (if (cdr list) (max (apply #'max (mapcar #'(lambda (w2) (mismatch (car list) w2)) (cdr list))) (max-mismatch (cdr list))) 0 )) (with-open-file (f "days-of-the-week.txt" :direction :input) (do* ((row (read-line f nil nil) (read-line f nil nil))) ((null row) t) (format t "~d ~a~%" (1+ (max-mismatch (SPLIT-SEQUENCE:split-sequence #\Space row))) row) ))
#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 Common_Lisp snippet to C++ and keep its semantics consistent.
(defun max-mismatch (list) (if (cdr list) (max (apply #'max (mapcar #'(lambda (w2) (mismatch (car list) w2)) (cdr list))) (max-mismatch (cdr list))) 0 )) (with-open-file (f "days-of-the-week.txt" :direction :input) (do* ((row (read-line f nil nil) (read-line f nil nil))) ((null row) t) (format t "~d ~a~%" (1+ (max-mismatch (SPLIT-SEQUENCE:split-sequence #\Space row))) row) ))
#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 Common_Lisp to Java without modifying what it does.
(defun max-mismatch (list) (if (cdr list) (max (apply #'max (mapcar #'(lambda (w2) (mismatch (car list) w2)) (cdr list))) (max-mismatch (cdr list))) 0 )) (with-open-file (f "days-of-the-week.txt" :direction :input) (do* ((row (read-line f nil nil) (read-line f nil nil))) ((null row) t) (format t "~d ~a~%" (1+ (max-mismatch (SPLIT-SEQUENCE:split-sequence #\Space row))) row) ))
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 Common_Lisp version.
(defun max-mismatch (list) (if (cdr list) (max (apply #'max (mapcar #'(lambda (w2) (mismatch (car list) w2)) (cdr list))) (max-mismatch (cdr list))) 0 )) (with-open-file (f "days-of-the-week.txt" :direction :input) (do* ((row (read-line f nil nil) (read-line f nil nil))) ((null row) t) (format t "~d ~a~%" (1+ (max-mismatch (SPLIT-SEQUENCE:split-sequence #\Space row))) row) ))
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 this program into Python but keep the logic exactly as in Common_Lisp.
(defun max-mismatch (list) (if (cdr list) (max (apply #'max (mapcar #'(lambda (w2) (mismatch (car list) w2)) (cdr list))) (max-mismatch (cdr list))) 0 )) (with-open-file (f "days-of-the-week.txt" :direction :input) (do* ((row (read-line f nil nil) (read-line f nil nil))) ((null row) t) (format t "~d ~a~%" (1+ (max-mismatch (SPLIT-SEQUENCE:split-sequence #\Space row))) row) ))
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.
(defun max-mismatch (list) (if (cdr list) (max (apply #'max (mapcar #'(lambda (w2) (mismatch (car list) w2)) (cdr list))) (max-mismatch (cdr list))) 0 )) (with-open-file (f "days-of-the-week.txt" :direction :input) (do* ((row (read-line f nil nil) (read-line f nil nil))) ((null row) t) (format t "~d ~a~%" (1+ (max-mismatch (SPLIT-SEQUENCE:split-sequence #\Space row))) row) ))
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 VB code behaves exactly like the original Common_Lisp snippet.
(defun max-mismatch (list) (if (cdr list) (max (apply #'max (mapcar #'(lambda (w2) (mismatch (car list) w2)) (cdr list))) (max-mismatch (cdr list))) 0 )) (with-open-file (f "days-of-the-week.txt" :direction :input) (do* ((row (read-line f nil nil) (read-line f nil nil))) ((null row) t) (format t "~d ~a~%" (1+ (max-mismatch (SPLIT-SEQUENCE:split-sequence #\Space row))) row) ))
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
Generate a VB translation of this Common_Lisp snippet without changing its computational steps.
(defun max-mismatch (list) (if (cdr list) (max (apply #'max (mapcar #'(lambda (w2) (mismatch (car list) w2)) (cdr list))) (max-mismatch (cdr list))) 0 )) (with-open-file (f "days-of-the-week.txt" :direction :input) (do* ((row (read-line f nil nil) (read-line f nil nil))) ((null row) t) (format t "~d ~a~%" (1+ (max-mismatch (SPLIT-SEQUENCE:split-sequence #\Space row))) row) ))
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
Rewrite the snippet below in Go so it works the same as the original Common_Lisp code.
(defun max-mismatch (list) (if (cdr list) (max (apply #'max (mapcar #'(lambda (w2) (mismatch (car list) w2)) (cdr list))) (max-mismatch (cdr list))) 0 )) (with-open-file (f "days-of-the-week.txt" :direction :input) (do* ((row (read-line f nil nil) (read-line f nil nil))) ((null row) t) (format t "~d ~a~%" (1+ (max-mismatch (SPLIT-SEQUENCE:split-sequence #\Space row))) row) ))
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 } } } }
Convert this Common_Lisp block to Go, preserving its control flow and logic.
(defun max-mismatch (list) (if (cdr list) (max (apply #'max (mapcar #'(lambda (w2) (mismatch (car list) w2)) (cdr list))) (max-mismatch (cdr list))) 0 )) (with-open-file (f "days-of-the-week.txt" :direction :input) (do* ((row (read-line f nil nil) (read-line f nil nil))) ((null row) t) (format t "~d ~a~%" (1+ (max-mismatch (SPLIT-SEQUENCE:split-sequence #\Space row))) row) ))
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 D code.
import std.conv; import std.exception; import std.range; import std.stdio; import std.string; void main() { foreach (size_t i, dstring line; File("days_of_week.txt").lines) { line = chomp(line); if (!line.empty) { auto days = line.split; enforce(days.length==7, text("There aren't 7 days in line ", i+1)); int[dstring] temp; foreach(day; days) { temp[day]++; } if (days.length < 7) { writeln(" ∞ ", line); continue; } int len = 1; while (true) { temp.clear(); foreach (day; days) { temp[day.take(len).array]++; } if (temp.length == 7) { writefln("%2d %s", 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; }
Maintain the same structure and functionality when rewriting this code in C.
import std.conv; import std.exception; import std.range; import std.stdio; import std.string; void main() { foreach (size_t i, dstring line; File("days_of_week.txt").lines) { line = chomp(line); if (!line.empty) { auto days = line.split; enforce(days.length==7, text("There aren't 7 days in line ", i+1)); int[dstring] temp; foreach(day; days) { temp[day]++; } if (days.length < 7) { writeln(" ∞ ", line); continue; } int len = 1; while (true) { temp.clear(); foreach (day; days) { temp[day.take(len).array]++; } if (temp.length == 7) { writefln("%2d %s", 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; }
Ensure the translated C# code behaves exactly like the original D snippet.
import std.conv; import std.exception; import std.range; import std.stdio; import std.string; void main() { foreach (size_t i, dstring line; File("days_of_week.txt").lines) { line = chomp(line); if (!line.empty) { auto days = line.split; enforce(days.length==7, text("There aren't 7 days in line ", i+1)); int[dstring] temp; foreach(day; days) { temp[day]++; } if (days.length < 7) { writeln(" ∞ ", line); continue; } int len = 1; while (true) { temp.clear(); foreach (day; days) { temp[day.take(len).array]++; } if (temp.length == 7) { writefln("%2d %s", len, line); break; } len++; } } } }
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++; } } } } } }
Preserve the algorithm and functionality while converting the code from D to C#.
import std.conv; import std.exception; import std.range; import std.stdio; import std.string; void main() { foreach (size_t i, dstring line; File("days_of_week.txt").lines) { line = chomp(line); if (!line.empty) { auto days = line.split; enforce(days.length==7, text("There aren't 7 days in line ", i+1)); int[dstring] temp; foreach(day; days) { temp[day]++; } if (days.length < 7) { writeln(" ∞ ", line); continue; } int len = 1; while (true) { temp.clear(); foreach (day; days) { temp[day.take(len).array]++; } if (temp.length == 7) { writefln("%2d %s", len, line); break; } len++; } } } }
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++; } } } } } }
Ensure the translated C++ code behaves exactly like the original D snippet.
import std.conv; import std.exception; import std.range; import std.stdio; import std.string; void main() { foreach (size_t i, dstring line; File("days_of_week.txt").lines) { line = chomp(line); if (!line.empty) { auto days = line.split; enforce(days.length==7, text("There aren't 7 days in line ", i+1)); int[dstring] temp; foreach(day; days) { temp[day]++; } if (days.length < 7) { writeln(" ∞ ", line); continue; } int len = 1; while (true) { temp.clear(); foreach (day; days) { temp[day.take(len).array]++; } if (temp.length == 7) { writefln("%2d %s", len, line); break; } len++; } } } }
#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; }
Translate this program into C++ but keep the logic exactly as in D.
import std.conv; import std.exception; import std.range; import std.stdio; import std.string; void main() { foreach (size_t i, dstring line; File("days_of_week.txt").lines) { line = chomp(line); if (!line.empty) { auto days = line.split; enforce(days.length==7, text("There aren't 7 days in line ", i+1)); int[dstring] temp; foreach(day; days) { temp[day]++; } if (days.length < 7) { writeln(" ∞ ", line); continue; } int len = 1; while (true) { temp.clear(); foreach (day; days) { temp[day.take(len).array]++; } if (temp.length == 7) { writefln("%2d %s", len, line); break; } len++; } } } }
#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; }
Can you help me rewrite this code in Java instead of D, keeping it the same logically?
import std.conv; import std.exception; import std.range; import std.stdio; import std.string; void main() { foreach (size_t i, dstring line; File("days_of_week.txt").lines) { line = chomp(line); if (!line.empty) { auto days = line.split; enforce(days.length==7, text("There aren't 7 days in line ", i+1)); int[dstring] temp; foreach(day; days) { temp[day]++; } if (days.length < 7) { writeln(" ∞ ", line); continue; } int len = 1; while (true) { temp.clear(); foreach (day; days) { temp[day.take(len).array]++; } if (temp.length == 7) { writefln("%2d %s", len, line); break; } len++; } } } }
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 D code snippet into Java without altering its behavior.
import std.conv; import std.exception; import std.range; import std.stdio; import std.string; void main() { foreach (size_t i, dstring line; File("days_of_week.txt").lines) { line = chomp(line); if (!line.empty) { auto days = line.split; enforce(days.length==7, text("There aren't 7 days in line ", i+1)); int[dstring] temp; foreach(day; days) { temp[day]++; } if (days.length < 7) { writeln(" ∞ ", line); continue; } int len = 1; while (true) { temp.clear(); foreach (day; days) { temp[day.take(len).array]++; } if (temp.length == 7) { writefln("%2d %s", len, line); break; } len++; } } } }
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 D code.
import std.conv; import std.exception; import std.range; import std.stdio; import std.string; void main() { foreach (size_t i, dstring line; File("days_of_week.txt").lines) { line = chomp(line); if (!line.empty) { auto days = line.split; enforce(days.length==7, text("There aren't 7 days in line ", i+1)); int[dstring] temp; foreach(day; days) { temp[day]++; } if (days.length < 7) { writeln(" ∞ ", line); continue; } int len = 1; while (true) { temp.clear(); foreach (day; days) { temp[day.take(len).array]++; } if (temp.length == 7) { writefln("%2d %s", len, line); break; } len++; } } } }
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 D to Python.
import std.conv; import std.exception; import std.range; import std.stdio; import std.string; void main() { foreach (size_t i, dstring line; File("days_of_week.txt").lines) { line = chomp(line); if (!line.empty) { auto days = line.split; enforce(days.length==7, text("There aren't 7 days in line ", i+1)); int[dstring] temp; foreach(day; days) { temp[day]++; } if (days.length < 7) { writeln(" ∞ ", line); continue; } int len = 1; while (true) { temp.clear(); foreach (day; days) { temp[day.take(len).array]++; } if (temp.length == 7) { writefln("%2d %s", len, line); break; } len++; } } } }
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 an equivalent VB version of this D code.
import std.conv; import std.exception; import std.range; import std.stdio; import std.string; void main() { foreach (size_t i, dstring line; File("days_of_week.txt").lines) { line = chomp(line); if (!line.empty) { auto days = line.split; enforce(days.length==7, text("There aren't 7 days in line ", i+1)); int[dstring] temp; foreach(day; days) { temp[day]++; } if (days.length < 7) { writeln(" ∞ ", line); continue; } int len = 1; while (true) { temp.clear(); foreach (day; days) { temp[day.take(len).array]++; } if (temp.length == 7) { writefln("%2d %s", len, line); break; } len++; } } } }
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
Generate a VB translation of this D snippet without changing its computational steps.
import std.conv; import std.exception; import std.range; import std.stdio; import std.string; void main() { foreach (size_t i, dstring line; File("days_of_week.txt").lines) { line = chomp(line); if (!line.empty) { auto days = line.split; enforce(days.length==7, text("There aren't 7 days in line ", i+1)); int[dstring] temp; foreach(day; days) { temp[day]++; } if (days.length < 7) { writeln(" ∞ ", line); continue; } int len = 1; while (true) { temp.clear(); foreach (day; days) { temp[day.take(len).array]++; } if (temp.length == 7) { writefln("%2d %s", len, line); break; } len++; } } } }
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
Generate an equivalent Go version of this D code.
import std.conv; import std.exception; import std.range; import std.stdio; import std.string; void main() { foreach (size_t i, dstring line; File("days_of_week.txt").lines) { line = chomp(line); if (!line.empty) { auto days = line.split; enforce(days.length==7, text("There aren't 7 days in line ", i+1)); int[dstring] temp; foreach(day; days) { temp[day]++; } if (days.length < 7) { writeln(" ∞ ", line); continue; } int len = 1; while (true) { temp.clear(); foreach (day; days) { temp[day.take(len).array]++; } if (temp.length == 7) { writefln("%2d %s", len, line); break; } len++; } } } }
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 D to Go, same semantics.
import std.conv; import std.exception; import std.range; import std.stdio; import std.string; void main() { foreach (size_t i, dstring line; File("days_of_week.txt").lines) { line = chomp(line); if (!line.empty) { auto days = line.split; enforce(days.length==7, text("There aren't 7 days in line ", i+1)); int[dstring] temp; foreach(day; days) { temp[day]++; } if (days.length < 7) { writeln(" ∞ ", line); continue; } int len = 1; while (true) { temp.clear(); foreach (day; days) { temp[day.take(len).array]++; } if (temp.length == 7) { writefln("%2d %s", len, line); break; } len++; } } } }
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 code in C as shown below in Delphi.
program Abbreviations_Automatic; uses System.SysUtils, System.Generics.Collections, System.IOUtils; function DistinctStrings(strs: TArray<string>): TArray<string>; begin var l := length(strs); var _set := TDictionary<string, Boolean>.Create; SetLength(result, 0); for var str in strs do begin if not _set.ContainsKey(str) then begin SetLength(result, Length(result) + 1); result[High(result)] := str; _set.AddOrSetValue(str, true); end; end; _set.free; end; function takeRunes(s: string; n: Integer): string; begin var i := 0; for var j := 0 to s.Length - 1 do begin if i = n then exit(s.Substring(0, j)); inc(i); end; Result := s; end; begin var lines := TFile.ReadAllLines('days_of_week.txt'); var lineCount := 0; while lineCount < length(Lines) do begin var line := lines[lineCount].Trim; inc(lineCount); if line.IsEmpty then begin Writeln; Continue; end; var days := line.Split([' '], TStringSplitOptions.ExcludeEmpty); var daysLen := Length(days); if daysLen <> 7 then begin Writeln('There aren''t 7 days in line', lineCount); Readln; halt; end; if Length(distinctStrings(days)) <> 7 then begin writeln(' infinity ', line); Continue; end; var abbrevLen := 0; while True do begin var abbrevs: TArray<string>; SetLength(abbrevs, daysLen); for var i := 0 to daysLen - 1 do abbrevs[i] := takeRunes(days[i], abbrevLen); if Length(distinctStrings(abbrevs)) = 7 then begin Writeln(abbrevLen.ToString.PadLeft(2).PadRight(3), line); Break; end; inc(abbrevLen); end; end; Readln; 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; }
Translate this program into C but keep the logic exactly as in Delphi.
program Abbreviations_Automatic; uses System.SysUtils, System.Generics.Collections, System.IOUtils; function DistinctStrings(strs: TArray<string>): TArray<string>; begin var l := length(strs); var _set := TDictionary<string, Boolean>.Create; SetLength(result, 0); for var str in strs do begin if not _set.ContainsKey(str) then begin SetLength(result, Length(result) + 1); result[High(result)] := str; _set.AddOrSetValue(str, true); end; end; _set.free; end; function takeRunes(s: string; n: Integer): string; begin var i := 0; for var j := 0 to s.Length - 1 do begin if i = n then exit(s.Substring(0, j)); inc(i); end; Result := s; end; begin var lines := TFile.ReadAllLines('days_of_week.txt'); var lineCount := 0; while lineCount < length(Lines) do begin var line := lines[lineCount].Trim; inc(lineCount); if line.IsEmpty then begin Writeln; Continue; end; var days := line.Split([' '], TStringSplitOptions.ExcludeEmpty); var daysLen := Length(days); if daysLen <> 7 then begin Writeln('There aren''t 7 days in line', lineCount); Readln; halt; end; if Length(distinctStrings(days)) <> 7 then begin writeln(' infinity ', line); Continue; end; var abbrevLen := 0; while True do begin var abbrevs: TArray<string>; SetLength(abbrevs, daysLen); for var i := 0 to daysLen - 1 do abbrevs[i] := takeRunes(days[i], abbrevLen); if Length(distinctStrings(abbrevs)) = 7 then begin Writeln(abbrevLen.ToString.PadLeft(2).PadRight(3), line); Break; end; inc(abbrevLen); end; end; Readln; 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; }
Write the same algorithm in C# as shown in this Delphi implementation.
program Abbreviations_Automatic; uses System.SysUtils, System.Generics.Collections, System.IOUtils; function DistinctStrings(strs: TArray<string>): TArray<string>; begin var l := length(strs); var _set := TDictionary<string, Boolean>.Create; SetLength(result, 0); for var str in strs do begin if not _set.ContainsKey(str) then begin SetLength(result, Length(result) + 1); result[High(result)] := str; _set.AddOrSetValue(str, true); end; end; _set.free; end; function takeRunes(s: string; n: Integer): string; begin var i := 0; for var j := 0 to s.Length - 1 do begin if i = n then exit(s.Substring(0, j)); inc(i); end; Result := s; end; begin var lines := TFile.ReadAllLines('days_of_week.txt'); var lineCount := 0; while lineCount < length(Lines) do begin var line := lines[lineCount].Trim; inc(lineCount); if line.IsEmpty then begin Writeln; Continue; end; var days := line.Split([' '], TStringSplitOptions.ExcludeEmpty); var daysLen := Length(days); if daysLen <> 7 then begin Writeln('There aren''t 7 days in line', lineCount); Readln; halt; end; if Length(distinctStrings(days)) <> 7 then begin writeln(' infinity ', line); Continue; end; var abbrevLen := 0; while True do begin var abbrevs: TArray<string>; SetLength(abbrevs, daysLen); for var i := 0 to daysLen - 1 do abbrevs[i] := takeRunes(days[i], abbrevLen); if Length(distinctStrings(abbrevs)) = 7 then begin Writeln(abbrevLen.ToString.PadLeft(2).PadRight(3), line); Break; end; inc(abbrevLen); end; end; Readln; 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++; } } } } } }
Write the same algorithm in C# as shown in this Delphi implementation.
program Abbreviations_Automatic; uses System.SysUtils, System.Generics.Collections, System.IOUtils; function DistinctStrings(strs: TArray<string>): TArray<string>; begin var l := length(strs); var _set := TDictionary<string, Boolean>.Create; SetLength(result, 0); for var str in strs do begin if not _set.ContainsKey(str) then begin SetLength(result, Length(result) + 1); result[High(result)] := str; _set.AddOrSetValue(str, true); end; end; _set.free; end; function takeRunes(s: string; n: Integer): string; begin var i := 0; for var j := 0 to s.Length - 1 do begin if i = n then exit(s.Substring(0, j)); inc(i); end; Result := s; end; begin var lines := TFile.ReadAllLines('days_of_week.txt'); var lineCount := 0; while lineCount < length(Lines) do begin var line := lines[lineCount].Trim; inc(lineCount); if line.IsEmpty then begin Writeln; Continue; end; var days := line.Split([' '], TStringSplitOptions.ExcludeEmpty); var daysLen := Length(days); if daysLen <> 7 then begin Writeln('There aren''t 7 days in line', lineCount); Readln; halt; end; if Length(distinctStrings(days)) <> 7 then begin writeln(' infinity ', line); Continue; end; var abbrevLen := 0; while True do begin var abbrevs: TArray<string>; SetLength(abbrevs, daysLen); for var i := 0 to daysLen - 1 do abbrevs[i] := takeRunes(days[i], abbrevLen); if Length(distinctStrings(abbrevs)) = 7 then begin Writeln(abbrevLen.ToString.PadLeft(2).PadRight(3), line); Break; end; inc(abbrevLen); end; end; Readln; 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++; } } } } } }
Port the provided Delphi code into C++ while preserving the original functionality.
program Abbreviations_Automatic; uses System.SysUtils, System.Generics.Collections, System.IOUtils; function DistinctStrings(strs: TArray<string>): TArray<string>; begin var l := length(strs); var _set := TDictionary<string, Boolean>.Create; SetLength(result, 0); for var str in strs do begin if not _set.ContainsKey(str) then begin SetLength(result, Length(result) + 1); result[High(result)] := str; _set.AddOrSetValue(str, true); end; end; _set.free; end; function takeRunes(s: string; n: Integer): string; begin var i := 0; for var j := 0 to s.Length - 1 do begin if i = n then exit(s.Substring(0, j)); inc(i); end; Result := s; end; begin var lines := TFile.ReadAllLines('days_of_week.txt'); var lineCount := 0; while lineCount < length(Lines) do begin var line := lines[lineCount].Trim; inc(lineCount); if line.IsEmpty then begin Writeln; Continue; end; var days := line.Split([' '], TStringSplitOptions.ExcludeEmpty); var daysLen := Length(days); if daysLen <> 7 then begin Writeln('There aren''t 7 days in line', lineCount); Readln; halt; end; if Length(distinctStrings(days)) <> 7 then begin writeln(' infinity ', line); Continue; end; var abbrevLen := 0; while True do begin var abbrevs: TArray<string>; SetLength(abbrevs, daysLen); for var i := 0 to daysLen - 1 do abbrevs[i] := takeRunes(days[i], abbrevLen); if Length(distinctStrings(abbrevs)) = 7 then begin Writeln(abbrevLen.ToString.PadLeft(2).PadRight(3), line); Break; end; inc(abbrevLen); end; end; Readln; 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; }
Please provide an equivalent version of this Delphi code in C++.
program Abbreviations_Automatic; uses System.SysUtils, System.Generics.Collections, System.IOUtils; function DistinctStrings(strs: TArray<string>): TArray<string>; begin var l := length(strs); var _set := TDictionary<string, Boolean>.Create; SetLength(result, 0); for var str in strs do begin if not _set.ContainsKey(str) then begin SetLength(result, Length(result) + 1); result[High(result)] := str; _set.AddOrSetValue(str, true); end; end; _set.free; end; function takeRunes(s: string; n: Integer): string; begin var i := 0; for var j := 0 to s.Length - 1 do begin if i = n then exit(s.Substring(0, j)); inc(i); end; Result := s; end; begin var lines := TFile.ReadAllLines('days_of_week.txt'); var lineCount := 0; while lineCount < length(Lines) do begin var line := lines[lineCount].Trim; inc(lineCount); if line.IsEmpty then begin Writeln; Continue; end; var days := line.Split([' '], TStringSplitOptions.ExcludeEmpty); var daysLen := Length(days); if daysLen <> 7 then begin Writeln('There aren''t 7 days in line', lineCount); Readln; halt; end; if Length(distinctStrings(days)) <> 7 then begin writeln(' infinity ', line); Continue; end; var abbrevLen := 0; while True do begin var abbrevs: TArray<string>; SetLength(abbrevs, daysLen); for var i := 0 to daysLen - 1 do abbrevs[i] := takeRunes(days[i], abbrevLen); if Length(distinctStrings(abbrevs)) = 7 then begin Writeln(abbrevLen.ToString.PadLeft(2).PadRight(3), line); Break; end; inc(abbrevLen); end; end; Readln; 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 an equivalent Java version of this Delphi code.
program Abbreviations_Automatic; uses System.SysUtils, System.Generics.Collections, System.IOUtils; function DistinctStrings(strs: TArray<string>): TArray<string>; begin var l := length(strs); var _set := TDictionary<string, Boolean>.Create; SetLength(result, 0); for var str in strs do begin if not _set.ContainsKey(str) then begin SetLength(result, Length(result) + 1); result[High(result)] := str; _set.AddOrSetValue(str, true); end; end; _set.free; end; function takeRunes(s: string; n: Integer): string; begin var i := 0; for var j := 0 to s.Length - 1 do begin if i = n then exit(s.Substring(0, j)); inc(i); end; Result := s; end; begin var lines := TFile.ReadAllLines('days_of_week.txt'); var lineCount := 0; while lineCount < length(Lines) do begin var line := lines[lineCount].Trim; inc(lineCount); if line.IsEmpty then begin Writeln; Continue; end; var days := line.Split([' '], TStringSplitOptions.ExcludeEmpty); var daysLen := Length(days); if daysLen <> 7 then begin Writeln('There aren''t 7 days in line', lineCount); Readln; halt; end; if Length(distinctStrings(days)) <> 7 then begin writeln(' infinity ', line); Continue; end; var abbrevLen := 0; while True do begin var abbrevs: TArray<string>; SetLength(abbrevs, daysLen); for var i := 0 to daysLen - 1 do abbrevs[i] := takeRunes(days[i], abbrevLen); if Length(distinctStrings(abbrevs)) = 7 then begin Writeln(abbrevLen.ToString.PadLeft(2).PadRight(3), line); Break; end; inc(abbrevLen); end; end; Readln; 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++; } } } }
Convert the following code from Delphi to Java, ensuring the logic remains intact.
program Abbreviations_Automatic; uses System.SysUtils, System.Generics.Collections, System.IOUtils; function DistinctStrings(strs: TArray<string>): TArray<string>; begin var l := length(strs); var _set := TDictionary<string, Boolean>.Create; SetLength(result, 0); for var str in strs do begin if not _set.ContainsKey(str) then begin SetLength(result, Length(result) + 1); result[High(result)] := str; _set.AddOrSetValue(str, true); end; end; _set.free; end; function takeRunes(s: string; n: Integer): string; begin var i := 0; for var j := 0 to s.Length - 1 do begin if i = n then exit(s.Substring(0, j)); inc(i); end; Result := s; end; begin var lines := TFile.ReadAllLines('days_of_week.txt'); var lineCount := 0; while lineCount < length(Lines) do begin var line := lines[lineCount].Trim; inc(lineCount); if line.IsEmpty then begin Writeln; Continue; end; var days := line.Split([' '], TStringSplitOptions.ExcludeEmpty); var daysLen := Length(days); if daysLen <> 7 then begin Writeln('There aren''t 7 days in line', lineCount); Readln; halt; end; if Length(distinctStrings(days)) <> 7 then begin writeln(' infinity ', line); Continue; end; var abbrevLen := 0; while True do begin var abbrevs: TArray<string>; SetLength(abbrevs, daysLen); for var i := 0 to daysLen - 1 do abbrevs[i] := takeRunes(days[i], abbrevLen); if Length(distinctStrings(abbrevs)) = 7 then begin Writeln(abbrevLen.ToString.PadLeft(2).PadRight(3), line); Break; end; inc(abbrevLen); end; end; Readln; 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++; } } } }
Preserve the algorithm and functionality while converting the code from Delphi to Python.
program Abbreviations_Automatic; uses System.SysUtils, System.Generics.Collections, System.IOUtils; function DistinctStrings(strs: TArray<string>): TArray<string>; begin var l := length(strs); var _set := TDictionary<string, Boolean>.Create; SetLength(result, 0); for var str in strs do begin if not _set.ContainsKey(str) then begin SetLength(result, Length(result) + 1); result[High(result)] := str; _set.AddOrSetValue(str, true); end; end; _set.free; end; function takeRunes(s: string; n: Integer): string; begin var i := 0; for var j := 0 to s.Length - 1 do begin if i = n then exit(s.Substring(0, j)); inc(i); end; Result := s; end; begin var lines := TFile.ReadAllLines('days_of_week.txt'); var lineCount := 0; while lineCount < length(Lines) do begin var line := lines[lineCount].Trim; inc(lineCount); if line.IsEmpty then begin Writeln; Continue; end; var days := line.Split([' '], TStringSplitOptions.ExcludeEmpty); var daysLen := Length(days); if daysLen <> 7 then begin Writeln('There aren''t 7 days in line', lineCount); Readln; halt; end; if Length(distinctStrings(days)) <> 7 then begin writeln(' infinity ', line); Continue; end; var abbrevLen := 0; while True do begin var abbrevs: TArray<string>; SetLength(abbrevs, daysLen); for var i := 0 to daysLen - 1 do abbrevs[i] := takeRunes(days[i], abbrevLen); if Length(distinctStrings(abbrevs)) = 7 then begin Writeln(abbrevLen.ToString.PadLeft(2).PadRight(3), line); Break; end; inc(abbrevLen); end; end; Readln; 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)
Can you help me rewrite this code in Python instead of Delphi, keeping it the same logically?
program Abbreviations_Automatic; uses System.SysUtils, System.Generics.Collections, System.IOUtils; function DistinctStrings(strs: TArray<string>): TArray<string>; begin var l := length(strs); var _set := TDictionary<string, Boolean>.Create; SetLength(result, 0); for var str in strs do begin if not _set.ContainsKey(str) then begin SetLength(result, Length(result) + 1); result[High(result)] := str; _set.AddOrSetValue(str, true); end; end; _set.free; end; function takeRunes(s: string; n: Integer): string; begin var i := 0; for var j := 0 to s.Length - 1 do begin if i = n then exit(s.Substring(0, j)); inc(i); end; Result := s; end; begin var lines := TFile.ReadAllLines('days_of_week.txt'); var lineCount := 0; while lineCount < length(Lines) do begin var line := lines[lineCount].Trim; inc(lineCount); if line.IsEmpty then begin Writeln; Continue; end; var days := line.Split([' '], TStringSplitOptions.ExcludeEmpty); var daysLen := Length(days); if daysLen <> 7 then begin Writeln('There aren''t 7 days in line', lineCount); Readln; halt; end; if Length(distinctStrings(days)) <> 7 then begin writeln(' infinity ', line); Continue; end; var abbrevLen := 0; while True do begin var abbrevs: TArray<string>; SetLength(abbrevs, daysLen); for var i := 0 to daysLen - 1 do abbrevs[i] := takeRunes(days[i], abbrevLen); if Length(distinctStrings(abbrevs)) = 7 then begin Writeln(abbrevLen.ToString.PadLeft(2).PadRight(3), line); Break; end; inc(abbrevLen); end; end; Readln; 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)
Keep all operations the same but rewrite the snippet in VB.
program Abbreviations_Automatic; uses System.SysUtils, System.Generics.Collections, System.IOUtils; function DistinctStrings(strs: TArray<string>): TArray<string>; begin var l := length(strs); var _set := TDictionary<string, Boolean>.Create; SetLength(result, 0); for var str in strs do begin if not _set.ContainsKey(str) then begin SetLength(result, Length(result) + 1); result[High(result)] := str; _set.AddOrSetValue(str, true); end; end; _set.free; end; function takeRunes(s: string; n: Integer): string; begin var i := 0; for var j := 0 to s.Length - 1 do begin if i = n then exit(s.Substring(0, j)); inc(i); end; Result := s; end; begin var lines := TFile.ReadAllLines('days_of_week.txt'); var lineCount := 0; while lineCount < length(Lines) do begin var line := lines[lineCount].Trim; inc(lineCount); if line.IsEmpty then begin Writeln; Continue; end; var days := line.Split([' '], TStringSplitOptions.ExcludeEmpty); var daysLen := Length(days); if daysLen <> 7 then begin Writeln('There aren''t 7 days in line', lineCount); Readln; halt; end; if Length(distinctStrings(days)) <> 7 then begin writeln(' infinity ', line); Continue; end; var abbrevLen := 0; while True do begin var abbrevs: TArray<string>; SetLength(abbrevs, daysLen); for var i := 0 to daysLen - 1 do abbrevs[i] := takeRunes(days[i], abbrevLen); if Length(distinctStrings(abbrevs)) = 7 then begin Writeln(abbrevLen.ToString.PadLeft(2).PadRight(3), line); Break; end; inc(abbrevLen); end; end; Readln; 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
Translate this program into VB but keep the logic exactly as in Delphi.
program Abbreviations_Automatic; uses System.SysUtils, System.Generics.Collections, System.IOUtils; function DistinctStrings(strs: TArray<string>): TArray<string>; begin var l := length(strs); var _set := TDictionary<string, Boolean>.Create; SetLength(result, 0); for var str in strs do begin if not _set.ContainsKey(str) then begin SetLength(result, Length(result) + 1); result[High(result)] := str; _set.AddOrSetValue(str, true); end; end; _set.free; end; function takeRunes(s: string; n: Integer): string; begin var i := 0; for var j := 0 to s.Length - 1 do begin if i = n then exit(s.Substring(0, j)); inc(i); end; Result := s; end; begin var lines := TFile.ReadAllLines('days_of_week.txt'); var lineCount := 0; while lineCount < length(Lines) do begin var line := lines[lineCount].Trim; inc(lineCount); if line.IsEmpty then begin Writeln; Continue; end; var days := line.Split([' '], TStringSplitOptions.ExcludeEmpty); var daysLen := Length(days); if daysLen <> 7 then begin Writeln('There aren''t 7 days in line', lineCount); Readln; halt; end; if Length(distinctStrings(days)) <> 7 then begin writeln(' infinity ', line); Continue; end; var abbrevLen := 0; while True do begin var abbrevs: TArray<string>; SetLength(abbrevs, daysLen); for var i := 0 to daysLen - 1 do abbrevs[i] := takeRunes(days[i], abbrevLen); if Length(distinctStrings(abbrevs)) = 7 then begin Writeln(abbrevLen.ToString.PadLeft(2).PadRight(3), line); Break; end; inc(abbrevLen); end; end; Readln; 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
Produce a functionally identical Go code for the snippet given in Delphi.
program Abbreviations_Automatic; uses System.SysUtils, System.Generics.Collections, System.IOUtils; function DistinctStrings(strs: TArray<string>): TArray<string>; begin var l := length(strs); var _set := TDictionary<string, Boolean>.Create; SetLength(result, 0); for var str in strs do begin if not _set.ContainsKey(str) then begin SetLength(result, Length(result) + 1); result[High(result)] := str; _set.AddOrSetValue(str, true); end; end; _set.free; end; function takeRunes(s: string; n: Integer): string; begin var i := 0; for var j := 0 to s.Length - 1 do begin if i = n then exit(s.Substring(0, j)); inc(i); end; Result := s; end; begin var lines := TFile.ReadAllLines('days_of_week.txt'); var lineCount := 0; while lineCount < length(Lines) do begin var line := lines[lineCount].Trim; inc(lineCount); if line.IsEmpty then begin Writeln; Continue; end; var days := line.Split([' '], TStringSplitOptions.ExcludeEmpty); var daysLen := Length(days); if daysLen <> 7 then begin Writeln('There aren''t 7 days in line', lineCount); Readln; halt; end; if Length(distinctStrings(days)) <> 7 then begin writeln(' infinity ', line); Continue; end; var abbrevLen := 0; while True do begin var abbrevs: TArray<string>; SetLength(abbrevs, daysLen); for var i := 0 to daysLen - 1 do abbrevs[i] := takeRunes(days[i], abbrevLen); if Length(distinctStrings(abbrevs)) = 7 then begin Writeln(abbrevLen.ToString.PadLeft(2).PadRight(3), line); Break; end; inc(abbrevLen); end; end; Readln; 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 } } } }