Instruction
stringlengths
45
106
input_code
stringlengths
1
13.7k
output_code
stringlengths
1
13.7k
Keep all operations the same but rewrite the snippet in PHP.
program main implicit none character(len=:),allocatable :: strings(:) strings=[ character(len=72) :: & '', & '"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln', & '..1111111111111111111111111111111111111111111111111111111111111117777888', & 'I never give ''em hell, I just tell the truth, and they think it''s hell.',& ' --- Harry S Truman' & ] call printme( trim(strings(1)), ' ' ) call printme( strings(2:4), ['-','7','.'] ) call printme( strings(5), [' ','-','r'] ) contains impure elemental subroutine printme(str,chr) character(len=*),intent(in) :: str character(len=1),intent(in) :: chr character(len=:),allocatable :: answer write(*,'(a)')repeat('=',9) write(*,'("IN: <<<",g0,">>>")')str answer=compact(str,chr) write(*,'("OUT: <<<",g0,">>>")')answer write(*,'("LENS: ",*(g0,1x))')"from",len(str),"to",len(answer),"for a change of",len(str)-len(answer) write(*,'("CHAR: ",g0)')chr end subroutine printme elemental function compact(str,charp) result (outstr) character(len=*),intent(in) :: str character(len=1),intent(in) :: charp character(len=:),allocatable :: outstr character(len=1) :: ch, last_one integer :: i, pio outstr=repeat(' ',len(str)) if(len(outstr)==0)return last_one=str(1:1) outstr(1:1)=last_one pio=1 do i=2,len(str) ch=str(i:i) pio=pio+merge(0,1, ch.eq.last_one.and.ch.eq.charp) outstr(pio:pio)=ch last_one=ch enddo outstr=outstr(:pio) end function compact end program main }
<?php function squeezeString($string, $squeezeChar) { $previousChar = null; $squeeze = ''; $charArray = preg_split('//u', $string, -1, PREG_SPLIT_NO_EMPTY); for ($i = 0 ; $i < count($charArray) ; $i++) { $currentChar = $charArray[$i]; if ($previousChar !== $currentChar || $currentChar !== $squeezeChar) { $squeeze .= $charArray[$i]; } $previousChar = $currentChar; } return $squeeze; } function isSqueezable($string, $squeezeChar) { return ($string !== squeezeString($string, $squeezeChar)); } $strings = array( ['-', '"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln '], ['1', '..1111111111111111111111111111111111111111111111111111111111111117777888'], ['l', "I never give 'em hell, I just tell the truth, and they think it's hell. "], [' ', ' --- Harry S Truman '], ['9', '0112223333444445555556666666777777778888888889999999999'], ['e', "The better the 4-wheel drive, the further you'll be from help when ya get stuck!"], ['k', "The better the 4-wheel drive, the further you'll be from help when ya get stuck!"], ); foreach ($strings as $params) { list($char, $original) = $params; echo 'Original Β : <<<', $original, '>>> (len=', mb_strlen($original), ')', PHP_EOL; if (isSqueezable($original, $char)) { $squeeze = squeezeString($original, $char); echo 'Squeeze(', $char, ')Β : <<<', $squeeze, '>>> (len=', mb_strlen($squeeze), ')', PHP_EOL, PHP_EOL; } else { echo 'Squeeze(', $char, ')Β : string is not squeezable (char=', $char, ')...', PHP_EOL, PHP_EOL; } }
Write the same code in PHP as shown below in Fortran.
program main implicit none character(len=:),allocatable :: strings(:) strings=[ character(len=72) :: & '', & '"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln', & '..1111111111111111111111111111111111111111111111111111111111111117777888', & 'I never give ''em hell, I just tell the truth, and they think it''s hell.',& ' --- Harry S Truman' & ] call printme( trim(strings(1)), ' ' ) call printme( strings(2:4), ['-','7','.'] ) call printme( strings(5), [' ','-','r'] ) contains impure elemental subroutine printme(str,chr) character(len=*),intent(in) :: str character(len=1),intent(in) :: chr character(len=:),allocatable :: answer write(*,'(a)')repeat('=',9) write(*,'("IN: <<<",g0,">>>")')str answer=compact(str,chr) write(*,'("OUT: <<<",g0,">>>")')answer write(*,'("LENS: ",*(g0,1x))')"from",len(str),"to",len(answer),"for a change of",len(str)-len(answer) write(*,'("CHAR: ",g0)')chr end subroutine printme elemental function compact(str,charp) result (outstr) character(len=*),intent(in) :: str character(len=1),intent(in) :: charp character(len=:),allocatable :: outstr character(len=1) :: ch, last_one integer :: i, pio outstr=repeat(' ',len(str)) if(len(outstr)==0)return last_one=str(1:1) outstr(1:1)=last_one pio=1 do i=2,len(str) ch=str(i:i) pio=pio+merge(0,1, ch.eq.last_one.and.ch.eq.charp) outstr(pio:pio)=ch last_one=ch enddo outstr=outstr(:pio) end function compact end program main }
<?php function squeezeString($string, $squeezeChar) { $previousChar = null; $squeeze = ''; $charArray = preg_split('//u', $string, -1, PREG_SPLIT_NO_EMPTY); for ($i = 0 ; $i < count($charArray) ; $i++) { $currentChar = $charArray[$i]; if ($previousChar !== $currentChar || $currentChar !== $squeezeChar) { $squeeze .= $charArray[$i]; } $previousChar = $currentChar; } return $squeeze; } function isSqueezable($string, $squeezeChar) { return ($string !== squeezeString($string, $squeezeChar)); } $strings = array( ['-', '"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln '], ['1', '..1111111111111111111111111111111111111111111111111111111111111117777888'], ['l', "I never give 'em hell, I just tell the truth, and they think it's hell. "], [' ', ' --- Harry S Truman '], ['9', '0112223333444445555556666666777777778888888889999999999'], ['e', "The better the 4-wheel drive, the further you'll be from help when ya get stuck!"], ['k', "The better the 4-wheel drive, the further you'll be from help when ya get stuck!"], ); foreach ($strings as $params) { list($char, $original) = $params; echo 'Original Β : <<<', $original, '>>> (len=', mb_strlen($original), ')', PHP_EOL; if (isSqueezable($original, $char)) { $squeeze = squeezeString($original, $char); echo 'Squeeze(', $char, ')Β : <<<', $squeeze, '>>> (len=', mb_strlen($squeeze), ')', PHP_EOL, PHP_EOL; } else { echo 'Squeeze(', $char, ')Β : string is not squeezable (char=', $char, ')...', PHP_EOL, PHP_EOL; } }
Generate an equivalent C version of this Groovy code.
class StringSqueezable { static void main(String[] args) { String[] testStrings = [ "", "\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln ", "..1111111111111111111111111111111111111111111111111111111111111117777888", "I never give 'em hell, I just tell the truth, and they think it's hell. ", " --- Harry S Truman ", "122333444455555666666777777788888888999999999", "The better the 4-wheel drive, the further you'll be from help when ya get stuck!", "headmistressship" ] String[] testChar = [" ", "-", "7", ".", " -r", "5", "e", "s"] for (int testNum = 0; testNum < testStrings.length; testNum++) { String s = testStrings[testNum] for (char c : testChar[testNum].toCharArray()) { String result = squeeze(s, c) System.out.printf("use: '%c'%nold: %2d <<<%s>>>%nnew: %2d <<<%s>>>%n%n", c, s.length(), s, result.length(), result) } } } private static String squeeze(String input, char include) { StringBuilder sb = new StringBuilder() for (int i = 0; i < input.length(); i++) { if (i == 0 || input.charAt(i - 1) != input.charAt(i) || (input.charAt(i - 1) == input.charAt(i) && input.charAt(i) != include)) { sb.append(input.charAt(i)) } } return sb.toString() } }
#include<string.h> #include<stdlib.h> #include<stdio.h> #define COLLAPSE 0 #define SQUEEZE 1 typedef struct charList{ char c; struct charList *next; } charList; int strcmpi(char str1[100],char str2[100]){ int len1 = strlen(str1), len2 = strlen(str2), i; if(len1!=len2){ return 1; } else{ for(i=0;i<len1;i++){ if((str1[i]>='A'&&str1[i]<='Z')&&(str2[i]>='a'&&str2[i]<='z')&&(str2[i]-65!=str1[i])) return 1; else if((str2[i]>='A'&&str2[i]<='Z')&&(str1[i]>='a'&&str1[i]<='z')&&(str1[i]-65!=str2[i])) return 1; else if(str1[i]!=str2[i]) return 1; } } return 0; } charList *strToCharList(char* str){ int len = strlen(str),i; charList *list, *iterator, *nextChar; list = (charList*)malloc(sizeof(charList)); list->c = str[0]; list->next = NULL; iterator = list; for(i=1;i<len;i++){ nextChar = (charList*)malloc(sizeof(charList)); nextChar->c = str[i]; nextChar->next = NULL; iterator->next = nextChar; iterator = nextChar; } return list; } char* charListToString(charList* list){ charList* iterator = list; int count = 0,i; char* str; while(iterator!=NULL){ count++; iterator = iterator->next; } str = (char*)malloc((count+1)*sizeof(char)); iterator = list; for(i=0;i<count;i++){ str[i] = iterator->c; iterator = iterator->next; } free(list); str[i] = '\0'; return str; } char* processString(char str[100],int operation, char squeezeChar){ charList *strList = strToCharList(str),*iterator = strList, *scout; if(operation==SQUEEZE){ while(iterator!=NULL){ if(iterator->c==squeezeChar){ scout = iterator->next; while(scout!=NULL && scout->c==squeezeChar){ iterator->next = scout->next; scout->next = NULL; free(scout); scout = iterator->next; } } iterator = iterator->next; } } else{ while(iterator!=NULL && iterator->next!=NULL){ if(iterator->c == (iterator->next)->c){ scout = iterator->next; squeezeChar = iterator->c; while(scout!=NULL && scout->c==squeezeChar){ iterator->next = scout->next; scout->next = NULL; free(scout); scout = iterator->next; } } iterator = iterator->next; } } return charListToString(strList); } void printResults(char originalString[100], char finalString[100], int operation, char squeezeChar){ if(operation==SQUEEZE){ printf("Specified OperationΒ : SQUEEZE\nTarget CharacterΒ : %c",squeezeChar); } else printf("Specified OperationΒ : COLLAPSE"); printf("\nOriginal %c%c%c%s%c%c%c\nLengthΒ : %d",174,174,174,originalString,175,175,175,(int)strlen(originalString)); printf("\nFinal %c%c%c%s%c%c%c\nLengthΒ : %d\n",174,174,174,finalString,175,175,175,(int)strlen(finalString)); } int main(int argc, char** argv){ int operation; char squeezeChar; if(argc<3||argc>4){ printf("UsageΒ : %s <SQUEEZE|COLLAPSE> <String to be processed> <Character to be squeezed, if operation is SQUEEZE>\n",argv[0]); return 0; } if(strcmpi(argv[1],"SQUEEZE")==0 && argc!=4){ scanf("Please enter characted to be squeezedΒ : %c",&squeezeChar); operation = SQUEEZE; } else if(argc==4){ operation = SQUEEZE; squeezeChar = argv[3][0]; } else if(strcmpi(argv[1],"COLLAPSE")==0){ operation = COLLAPSE; } if(strlen(argv[2])<2){ printResults(argv[2],argv[2],operation,squeezeChar); } else{ printResults(argv[2],processString(argv[2],operation,squeezeChar),operation,squeezeChar); } return 0; }
Write the same code in C as shown below in Groovy.
class StringSqueezable { static void main(String[] args) { String[] testStrings = [ "", "\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln ", "..1111111111111111111111111111111111111111111111111111111111111117777888", "I never give 'em hell, I just tell the truth, and they think it's hell. ", " --- Harry S Truman ", "122333444455555666666777777788888888999999999", "The better the 4-wheel drive, the further you'll be from help when ya get stuck!", "headmistressship" ] String[] testChar = [" ", "-", "7", ".", " -r", "5", "e", "s"] for (int testNum = 0; testNum < testStrings.length; testNum++) { String s = testStrings[testNum] for (char c : testChar[testNum].toCharArray()) { String result = squeeze(s, c) System.out.printf("use: '%c'%nold: %2d <<<%s>>>%nnew: %2d <<<%s>>>%n%n", c, s.length(), s, result.length(), result) } } } private static String squeeze(String input, char include) { StringBuilder sb = new StringBuilder() for (int i = 0; i < input.length(); i++) { if (i == 0 || input.charAt(i - 1) != input.charAt(i) || (input.charAt(i - 1) == input.charAt(i) && input.charAt(i) != include)) { sb.append(input.charAt(i)) } } return sb.toString() } }
#include<string.h> #include<stdlib.h> #include<stdio.h> #define COLLAPSE 0 #define SQUEEZE 1 typedef struct charList{ char c; struct charList *next; } charList; int strcmpi(char str1[100],char str2[100]){ int len1 = strlen(str1), len2 = strlen(str2), i; if(len1!=len2){ return 1; } else{ for(i=0;i<len1;i++){ if((str1[i]>='A'&&str1[i]<='Z')&&(str2[i]>='a'&&str2[i]<='z')&&(str2[i]-65!=str1[i])) return 1; else if((str2[i]>='A'&&str2[i]<='Z')&&(str1[i]>='a'&&str1[i]<='z')&&(str1[i]-65!=str2[i])) return 1; else if(str1[i]!=str2[i]) return 1; } } return 0; } charList *strToCharList(char* str){ int len = strlen(str),i; charList *list, *iterator, *nextChar; list = (charList*)malloc(sizeof(charList)); list->c = str[0]; list->next = NULL; iterator = list; for(i=1;i<len;i++){ nextChar = (charList*)malloc(sizeof(charList)); nextChar->c = str[i]; nextChar->next = NULL; iterator->next = nextChar; iterator = nextChar; } return list; } char* charListToString(charList* list){ charList* iterator = list; int count = 0,i; char* str; while(iterator!=NULL){ count++; iterator = iterator->next; } str = (char*)malloc((count+1)*sizeof(char)); iterator = list; for(i=0;i<count;i++){ str[i] = iterator->c; iterator = iterator->next; } free(list); str[i] = '\0'; return str; } char* processString(char str[100],int operation, char squeezeChar){ charList *strList = strToCharList(str),*iterator = strList, *scout; if(operation==SQUEEZE){ while(iterator!=NULL){ if(iterator->c==squeezeChar){ scout = iterator->next; while(scout!=NULL && scout->c==squeezeChar){ iterator->next = scout->next; scout->next = NULL; free(scout); scout = iterator->next; } } iterator = iterator->next; } } else{ while(iterator!=NULL && iterator->next!=NULL){ if(iterator->c == (iterator->next)->c){ scout = iterator->next; squeezeChar = iterator->c; while(scout!=NULL && scout->c==squeezeChar){ iterator->next = scout->next; scout->next = NULL; free(scout); scout = iterator->next; } } iterator = iterator->next; } } return charListToString(strList); } void printResults(char originalString[100], char finalString[100], int operation, char squeezeChar){ if(operation==SQUEEZE){ printf("Specified OperationΒ : SQUEEZE\nTarget CharacterΒ : %c",squeezeChar); } else printf("Specified OperationΒ : COLLAPSE"); printf("\nOriginal %c%c%c%s%c%c%c\nLengthΒ : %d",174,174,174,originalString,175,175,175,(int)strlen(originalString)); printf("\nFinal %c%c%c%s%c%c%c\nLengthΒ : %d\n",174,174,174,finalString,175,175,175,(int)strlen(finalString)); } int main(int argc, char** argv){ int operation; char squeezeChar; if(argc<3||argc>4){ printf("UsageΒ : %s <SQUEEZE|COLLAPSE> <String to be processed> <Character to be squeezed, if operation is SQUEEZE>\n",argv[0]); return 0; } if(strcmpi(argv[1],"SQUEEZE")==0 && argc!=4){ scanf("Please enter characted to be squeezedΒ : %c",&squeezeChar); operation = SQUEEZE; } else if(argc==4){ operation = SQUEEZE; squeezeChar = argv[3][0]; } else if(strcmpi(argv[1],"COLLAPSE")==0){ operation = COLLAPSE; } if(strlen(argv[2])<2){ printResults(argv[2],argv[2],operation,squeezeChar); } else{ printResults(argv[2],processString(argv[2],operation,squeezeChar),operation,squeezeChar); } return 0; }
Ensure the translated C# code behaves exactly like the original Groovy snippet.
class StringSqueezable { static void main(String[] args) { String[] testStrings = [ "", "\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln ", "..1111111111111111111111111111111111111111111111111111111111111117777888", "I never give 'em hell, I just tell the truth, and they think it's hell. ", " --- Harry S Truman ", "122333444455555666666777777788888888999999999", "The better the 4-wheel drive, the further you'll be from help when ya get stuck!", "headmistressship" ] String[] testChar = [" ", "-", "7", ".", " -r", "5", "e", "s"] for (int testNum = 0; testNum < testStrings.length; testNum++) { String s = testStrings[testNum] for (char c : testChar[testNum].toCharArray()) { String result = squeeze(s, c) System.out.printf("use: '%c'%nold: %2d <<<%s>>>%nnew: %2d <<<%s>>>%n%n", c, s.length(), s, result.length(), result) } } } private static String squeeze(String input, char include) { StringBuilder sb = new StringBuilder() for (int i = 0; i < input.length(); i++) { if (i == 0 || input.charAt(i - 1) != input.charAt(i) || (input.charAt(i - 1) == input.charAt(i) && input.charAt(i) != include)) { sb.append(input.charAt(i)) } } return sb.toString() } }
using System; using static System.Linq.Enumerable; public class Program { static void Main() { SqueezeAndPrint("", ' '); SqueezeAndPrint("\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln ", '-'); SqueezeAndPrint("..1111111111111111111111111111111111111111111111111111111111111117777888", '7'); SqueezeAndPrint("I never give 'em hell, I just tell the truth, and they think it's hell. ", '.'); string s = " --- Harry S Truman "; SqueezeAndPrint(s, ' '); SqueezeAndPrint(s, '-'); SqueezeAndPrint(s, 'r'); } static void SqueezeAndPrint(string s, char c) { Console.WriteLine($"squeeze: '{c}'"); Console.WriteLine($"old: {s.Length} «««{s}»»»"); s = Squeeze(s, c); Console.WriteLine($"new: {s.Length} «««{s}»»»"); } static string Squeeze(string s, char c) => string.IsNullOrEmpty(s) ? "" : s[0] + new string(Range(1, s.Length - 1).Where(i => s[i] != c || s[i] != s[i - 1]).Select(i => s[i]).ToArray()); }
Convert this Groovy snippet to C# and keep its semantics consistent.
class StringSqueezable { static void main(String[] args) { String[] testStrings = [ "", "\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln ", "..1111111111111111111111111111111111111111111111111111111111111117777888", "I never give 'em hell, I just tell the truth, and they think it's hell. ", " --- Harry S Truman ", "122333444455555666666777777788888888999999999", "The better the 4-wheel drive, the further you'll be from help when ya get stuck!", "headmistressship" ] String[] testChar = [" ", "-", "7", ".", " -r", "5", "e", "s"] for (int testNum = 0; testNum < testStrings.length; testNum++) { String s = testStrings[testNum] for (char c : testChar[testNum].toCharArray()) { String result = squeeze(s, c) System.out.printf("use: '%c'%nold: %2d <<<%s>>>%nnew: %2d <<<%s>>>%n%n", c, s.length(), s, result.length(), result) } } } private static String squeeze(String input, char include) { StringBuilder sb = new StringBuilder() for (int i = 0; i < input.length(); i++) { if (i == 0 || input.charAt(i - 1) != input.charAt(i) || (input.charAt(i - 1) == input.charAt(i) && input.charAt(i) != include)) { sb.append(input.charAt(i)) } } return sb.toString() } }
using System; using static System.Linq.Enumerable; public class Program { static void Main() { SqueezeAndPrint("", ' '); SqueezeAndPrint("\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln ", '-'); SqueezeAndPrint("..1111111111111111111111111111111111111111111111111111111111111117777888", '7'); SqueezeAndPrint("I never give 'em hell, I just tell the truth, and they think it's hell. ", '.'); string s = " --- Harry S Truman "; SqueezeAndPrint(s, ' '); SqueezeAndPrint(s, '-'); SqueezeAndPrint(s, 'r'); } static void SqueezeAndPrint(string s, char c) { Console.WriteLine($"squeeze: '{c}'"); Console.WriteLine($"old: {s.Length} «««{s}»»»"); s = Squeeze(s, c); Console.WriteLine($"new: {s.Length} «««{s}»»»"); } static string Squeeze(string s, char c) => string.IsNullOrEmpty(s) ? "" : s[0] + new string(Range(1, s.Length - 1).Where(i => s[i] != c || s[i] != s[i - 1]).Select(i => s[i]).ToArray()); }
Write the same code in C++ as shown below in Groovy.
class StringSqueezable { static void main(String[] args) { String[] testStrings = [ "", "\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln ", "..1111111111111111111111111111111111111111111111111111111111111117777888", "I never give 'em hell, I just tell the truth, and they think it's hell. ", " --- Harry S Truman ", "122333444455555666666777777788888888999999999", "The better the 4-wheel drive, the further you'll be from help when ya get stuck!", "headmistressship" ] String[] testChar = [" ", "-", "7", ".", " -r", "5", "e", "s"] for (int testNum = 0; testNum < testStrings.length; testNum++) { String s = testStrings[testNum] for (char c : testChar[testNum].toCharArray()) { String result = squeeze(s, c) System.out.printf("use: '%c'%nold: %2d <<<%s>>>%nnew: %2d <<<%s>>>%n%n", c, s.length(), s, result.length(), result) } } } private static String squeeze(String input, char include) { StringBuilder sb = new StringBuilder() for (int i = 0; i < input.length(); i++) { if (i == 0 || input.charAt(i - 1) != input.charAt(i) || (input.charAt(i - 1) == input.charAt(i) && input.charAt(i) != include)) { sb.append(input.charAt(i)) } } return sb.toString() } }
#include <algorithm> #include <string> #include <iostream> template<typename char_type> std::basic_string<char_type> squeeze(std::basic_string<char_type> str, char_type ch) { auto i = std::unique(str.begin(), str.end(), [ch](char_type a, char_type b) { return a == ch && b == ch; }); str.erase(i, str.end()); return str; } void test(const std::string& str, char ch) { std::cout << "character: '" << ch << "'\n"; std::cout << "original: <<<" << str << ">>>, length: " << str.length() << '\n'; std::string squeezed(squeeze(str, ch)); std::cout << "result: <<<" << squeezed << ">>>, length: " << squeezed.length() << '\n'; std::cout << '\n'; } int main(int argc, char** argv) { test("", ' '); test("\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln ", '-'); test("..1111111111111111111111111111111111111111111111111111111111111117777888", '7'); test("I never give 'em hell, I just tell the truth, and they think it's hell. ", '.'); std::string truman(" --- Harry S Truman "); test(truman, ' '); test(truman, '-'); test(truman, 'r'); return 0; }
Maintain the same structure and functionality when rewriting this code in C++.
class StringSqueezable { static void main(String[] args) { String[] testStrings = [ "", "\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln ", "..1111111111111111111111111111111111111111111111111111111111111117777888", "I never give 'em hell, I just tell the truth, and they think it's hell. ", " --- Harry S Truman ", "122333444455555666666777777788888888999999999", "The better the 4-wheel drive, the further you'll be from help when ya get stuck!", "headmistressship" ] String[] testChar = [" ", "-", "7", ".", " -r", "5", "e", "s"] for (int testNum = 0; testNum < testStrings.length; testNum++) { String s = testStrings[testNum] for (char c : testChar[testNum].toCharArray()) { String result = squeeze(s, c) System.out.printf("use: '%c'%nold: %2d <<<%s>>>%nnew: %2d <<<%s>>>%n%n", c, s.length(), s, result.length(), result) } } } private static String squeeze(String input, char include) { StringBuilder sb = new StringBuilder() for (int i = 0; i < input.length(); i++) { if (i == 0 || input.charAt(i - 1) != input.charAt(i) || (input.charAt(i - 1) == input.charAt(i) && input.charAt(i) != include)) { sb.append(input.charAt(i)) } } return sb.toString() } }
#include <algorithm> #include <string> #include <iostream> template<typename char_type> std::basic_string<char_type> squeeze(std::basic_string<char_type> str, char_type ch) { auto i = std::unique(str.begin(), str.end(), [ch](char_type a, char_type b) { return a == ch && b == ch; }); str.erase(i, str.end()); return str; } void test(const std::string& str, char ch) { std::cout << "character: '" << ch << "'\n"; std::cout << "original: <<<" << str << ">>>, length: " << str.length() << '\n'; std::string squeezed(squeeze(str, ch)); std::cout << "result: <<<" << squeezed << ">>>, length: " << squeezed.length() << '\n'; std::cout << '\n'; } int main(int argc, char** argv) { test("", ' '); test("\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln ", '-'); test("..1111111111111111111111111111111111111111111111111111111111111117777888", '7'); test("I never give 'em hell, I just tell the truth, and they think it's hell. ", '.'); std::string truman(" --- Harry S Truman "); test(truman, ' '); test(truman, '-'); test(truman, 'r'); return 0; }
Produce a language-to-language conversion: from Groovy to Java, same semantics.
class StringSqueezable { static void main(String[] args) { String[] testStrings = [ "", "\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln ", "..1111111111111111111111111111111111111111111111111111111111111117777888", "I never give 'em hell, I just tell the truth, and they think it's hell. ", " --- Harry S Truman ", "122333444455555666666777777788888888999999999", "The better the 4-wheel drive, the further you'll be from help when ya get stuck!", "headmistressship" ] String[] testChar = [" ", "-", "7", ".", " -r", "5", "e", "s"] for (int testNum = 0; testNum < testStrings.length; testNum++) { String s = testStrings[testNum] for (char c : testChar[testNum].toCharArray()) { String result = squeeze(s, c) System.out.printf("use: '%c'%nold: %2d <<<%s>>>%nnew: %2d <<<%s>>>%n%n", c, s.length(), s, result.length(), result) } } } private static String squeeze(String input, char include) { StringBuilder sb = new StringBuilder() for (int i = 0; i < input.length(); i++) { if (i == 0 || input.charAt(i - 1) != input.charAt(i) || (input.charAt(i - 1) == input.charAt(i) && input.charAt(i) != include)) { sb.append(input.charAt(i)) } } return sb.toString() } }
public class StringSqueezable { public static void main(String[] args) { String[] testStrings = new String[] { "", "\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln ", "..1111111111111111111111111111111111111111111111111111111111111117777888", "I never give 'em hell, I just tell the truth, and they think it's hell. ", " --- Harry S Truman ", "122333444455555666666777777788888888999999999", "The better the 4-wheel drive, the further you'll be from help when ya get stuck!", "headmistressship"}; String[] testChar = new String[] { " ", "-", "7", ".", " -r", "5", "e", "s"}; for ( int testNum = 0 ; testNum < testStrings.length ; testNum++ ) { String s = testStrings[testNum]; for ( char c : testChar[testNum].toCharArray() ) { String result = squeeze(s, c); System.out.printf("use: '%c'%nold: %2d <<<%s>>>%nnew: %2d <<<%s>>>%n%n", c, s.length(), s, result.length(), result); } } } private static String squeeze(String in, char include) { StringBuilder sb = new StringBuilder(); for ( int i = 0 ; i < in.length() ; i++ ) { if ( i == 0 || in.charAt(i-1) != in.charAt(i) || (in.charAt(i-1) == in.charAt(i) && in.charAt(i) != include)) { sb.append(in.charAt(i)); } } return sb.toString(); } }
Produce a functionally identical Java code for the snippet given in Groovy.
class StringSqueezable { static void main(String[] args) { String[] testStrings = [ "", "\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln ", "..1111111111111111111111111111111111111111111111111111111111111117777888", "I never give 'em hell, I just tell the truth, and they think it's hell. ", " --- Harry S Truman ", "122333444455555666666777777788888888999999999", "The better the 4-wheel drive, the further you'll be from help when ya get stuck!", "headmistressship" ] String[] testChar = [" ", "-", "7", ".", " -r", "5", "e", "s"] for (int testNum = 0; testNum < testStrings.length; testNum++) { String s = testStrings[testNum] for (char c : testChar[testNum].toCharArray()) { String result = squeeze(s, c) System.out.printf("use: '%c'%nold: %2d <<<%s>>>%nnew: %2d <<<%s>>>%n%n", c, s.length(), s, result.length(), result) } } } private static String squeeze(String input, char include) { StringBuilder sb = new StringBuilder() for (int i = 0; i < input.length(); i++) { if (i == 0 || input.charAt(i - 1) != input.charAt(i) || (input.charAt(i - 1) == input.charAt(i) && input.charAt(i) != include)) { sb.append(input.charAt(i)) } } return sb.toString() } }
public class StringSqueezable { public static void main(String[] args) { String[] testStrings = new String[] { "", "\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln ", "..1111111111111111111111111111111111111111111111111111111111111117777888", "I never give 'em hell, I just tell the truth, and they think it's hell. ", " --- Harry S Truman ", "122333444455555666666777777788888888999999999", "The better the 4-wheel drive, the further you'll be from help when ya get stuck!", "headmistressship"}; String[] testChar = new String[] { " ", "-", "7", ".", " -r", "5", "e", "s"}; for ( int testNum = 0 ; testNum < testStrings.length ; testNum++ ) { String s = testStrings[testNum]; for ( char c : testChar[testNum].toCharArray() ) { String result = squeeze(s, c); System.out.printf("use: '%c'%nold: %2d <<<%s>>>%nnew: %2d <<<%s>>>%n%n", c, s.length(), s, result.length(), result); } } } private static String squeeze(String in, char include) { StringBuilder sb = new StringBuilder(); for ( int i = 0 ; i < in.length() ; i++ ) { if ( i == 0 || in.charAt(i-1) != in.charAt(i) || (in.charAt(i-1) == in.charAt(i) && in.charAt(i) != include)) { sb.append(in.charAt(i)); } } return sb.toString(); } }
Produce a functionally identical Python code for the snippet given in Groovy.
class StringSqueezable { static void main(String[] args) { String[] testStrings = [ "", "\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln ", "..1111111111111111111111111111111111111111111111111111111111111117777888", "I never give 'em hell, I just tell the truth, and they think it's hell. ", " --- Harry S Truman ", "122333444455555666666777777788888888999999999", "The better the 4-wheel drive, the further you'll be from help when ya get stuck!", "headmistressship" ] String[] testChar = [" ", "-", "7", ".", " -r", "5", "e", "s"] for (int testNum = 0; testNum < testStrings.length; testNum++) { String s = testStrings[testNum] for (char c : testChar[testNum].toCharArray()) { String result = squeeze(s, c) System.out.printf("use: '%c'%nold: %2d <<<%s>>>%nnew: %2d <<<%s>>>%n%n", c, s.length(), s, result.length(), result) } } } private static String squeeze(String input, char include) { StringBuilder sb = new StringBuilder() for (int i = 0; i < input.length(); i++) { if (i == 0 || input.charAt(i - 1) != input.charAt(i) || (input.charAt(i - 1) == input.charAt(i) && input.charAt(i) != include)) { sb.append(input.charAt(i)) } } return sb.toString() } }
from itertools import groupby def squeezer(s, txt): return ''.join(item if item == s else ''.join(grp) for item, grp in groupby(txt)) if __name__ == '__main__': strings = [ "", '"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln ', "..1111111111111111111111111111111111111111111111111111111111111117777888", "I never give 'em hell, I just tell the truth, and they think it's hell. ", " --- Harry S Truman ", "The better the 4-wheel drive, the further you'll be from help when ya get stuck!", "headmistressship", "aardvark", "πŸ˜πŸ˜€πŸ™ŒπŸ’ƒπŸ˜πŸ˜πŸ˜πŸ™Œ", ] squeezers = ' ,-,7,., -r,e,s,a,😍'.split(',') for txt, chars in zip(strings, squeezers): this = "Original" print(f"\n{this:14} Size: {len(txt)} «««{txt}»»»" ) for ch in chars: this = f"Squeezer '{ch}'" sqz = squeezer(ch, txt) print(f"{this:>14} Size: {len(sqz)} «««{sqz}»»»" )
Change the following Groovy code into Python without altering its purpose.
class StringSqueezable { static void main(String[] args) { String[] testStrings = [ "", "\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln ", "..1111111111111111111111111111111111111111111111111111111111111117777888", "I never give 'em hell, I just tell the truth, and they think it's hell. ", " --- Harry S Truman ", "122333444455555666666777777788888888999999999", "The better the 4-wheel drive, the further you'll be from help when ya get stuck!", "headmistressship" ] String[] testChar = [" ", "-", "7", ".", " -r", "5", "e", "s"] for (int testNum = 0; testNum < testStrings.length; testNum++) { String s = testStrings[testNum] for (char c : testChar[testNum].toCharArray()) { String result = squeeze(s, c) System.out.printf("use: '%c'%nold: %2d <<<%s>>>%nnew: %2d <<<%s>>>%n%n", c, s.length(), s, result.length(), result) } } } private static String squeeze(String input, char include) { StringBuilder sb = new StringBuilder() for (int i = 0; i < input.length(); i++) { if (i == 0 || input.charAt(i - 1) != input.charAt(i) || (input.charAt(i - 1) == input.charAt(i) && input.charAt(i) != include)) { sb.append(input.charAt(i)) } } return sb.toString() } }
from itertools import groupby def squeezer(s, txt): return ''.join(item if item == s else ''.join(grp) for item, grp in groupby(txt)) if __name__ == '__main__': strings = [ "", '"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln ', "..1111111111111111111111111111111111111111111111111111111111111117777888", "I never give 'em hell, I just tell the truth, and they think it's hell. ", " --- Harry S Truman ", "The better the 4-wheel drive, the further you'll be from help when ya get stuck!", "headmistressship", "aardvark", "πŸ˜πŸ˜€πŸ™ŒπŸ’ƒπŸ˜πŸ˜πŸ˜πŸ™Œ", ] squeezers = ' ,-,7,., -r,e,s,a,😍'.split(',') for txt, chars in zip(strings, squeezers): this = "Original" print(f"\n{this:14} Size: {len(txt)} «««{txt}»»»" ) for ch in chars: this = f"Squeezer '{ch}'" sqz = squeezer(ch, txt) print(f"{this:>14} Size: {len(sqz)} «««{sqz}»»»" )
Write the same code in VB as shown below in Groovy.
class StringSqueezable { static void main(String[] args) { String[] testStrings = [ "", "\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln ", "..1111111111111111111111111111111111111111111111111111111111111117777888", "I never give 'em hell, I just tell the truth, and they think it's hell. ", " --- Harry S Truman ", "122333444455555666666777777788888888999999999", "The better the 4-wheel drive, the further you'll be from help when ya get stuck!", "headmistressship" ] String[] testChar = [" ", "-", "7", ".", " -r", "5", "e", "s"] for (int testNum = 0; testNum < testStrings.length; testNum++) { String s = testStrings[testNum] for (char c : testChar[testNum].toCharArray()) { String result = squeeze(s, c) System.out.printf("use: '%c'%nold: %2d <<<%s>>>%nnew: %2d <<<%s>>>%n%n", c, s.length(), s, result.length(), result) } } } private static String squeeze(String input, char include) { StringBuilder sb = new StringBuilder() for (int i = 0; i < input.length(); i++) { if (i == 0 || input.charAt(i - 1) != input.charAt(i) || (input.charAt(i - 1) == input.charAt(i) && input.charAt(i) != include)) { sb.append(input.charAt(i)) } } return sb.toString() } }
Imports System.Linq.Enumerable Module Module1 Function Squeeze(s As String, c As Char) As String If String.IsNullOrEmpty(s) Then Return "" End If Return s(0) + New String(Range(1, s.Length - 1).Where(Function(i) s(i) <> c OrElse s(i) <> s(i - 1)).Select(Function(i) s(i)).ToArray()) End Function Sub SqueezeAndPrint(s As String, c As Char) Console.WriteLine("squeeze: Console.WriteLine("old: {0} «««{1}»»»", s.Length, s) s = Squeeze(s, c) Console.WriteLine("new: {0} «««{1}»»»", s.Length, s) End Sub Sub Main() Const QUOTE = """" SqueezeAndPrint("", " ") SqueezeAndPrint(QUOTE & "If I were two-faced, would I be wearing this one?" & QUOTE & " --- Abraham Lincoln ", "-") SqueezeAndPrint("..1111111111111111111111111111111111111111111111111111111111111117777888", "7") SqueezeAndPrint("I never give Dim s = " --- Harry S Truman " SqueezeAndPrint(s, " ") SqueezeAndPrint(s, "-") SqueezeAndPrint(s, "r") End Sub End Module
Convert the following code from Groovy to VB, ensuring the logic remains intact.
class StringSqueezable { static void main(String[] args) { String[] testStrings = [ "", "\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln ", "..1111111111111111111111111111111111111111111111111111111111111117777888", "I never give 'em hell, I just tell the truth, and they think it's hell. ", " --- Harry S Truman ", "122333444455555666666777777788888888999999999", "The better the 4-wheel drive, the further you'll be from help when ya get stuck!", "headmistressship" ] String[] testChar = [" ", "-", "7", ".", " -r", "5", "e", "s"] for (int testNum = 0; testNum < testStrings.length; testNum++) { String s = testStrings[testNum] for (char c : testChar[testNum].toCharArray()) { String result = squeeze(s, c) System.out.printf("use: '%c'%nold: %2d <<<%s>>>%nnew: %2d <<<%s>>>%n%n", c, s.length(), s, result.length(), result) } } } private static String squeeze(String input, char include) { StringBuilder sb = new StringBuilder() for (int i = 0; i < input.length(); i++) { if (i == 0 || input.charAt(i - 1) != input.charAt(i) || (input.charAt(i - 1) == input.charAt(i) && input.charAt(i) != include)) { sb.append(input.charAt(i)) } } return sb.toString() } }
Imports System.Linq.Enumerable Module Module1 Function Squeeze(s As String, c As Char) As String If String.IsNullOrEmpty(s) Then Return "" End If Return s(0) + New String(Range(1, s.Length - 1).Where(Function(i) s(i) <> c OrElse s(i) <> s(i - 1)).Select(Function(i) s(i)).ToArray()) End Function Sub SqueezeAndPrint(s As String, c As Char) Console.WriteLine("squeeze: Console.WriteLine("old: {0} «««{1}»»»", s.Length, s) s = Squeeze(s, c) Console.WriteLine("new: {0} «««{1}»»»", s.Length, s) End Sub Sub Main() Const QUOTE = """" SqueezeAndPrint("", " ") SqueezeAndPrint(QUOTE & "If I were two-faced, would I be wearing this one?" & QUOTE & " --- Abraham Lincoln ", "-") SqueezeAndPrint("..1111111111111111111111111111111111111111111111111111111111111117777888", "7") SqueezeAndPrint("I never give Dim s = " --- Harry S Truman " SqueezeAndPrint(s, " ") SqueezeAndPrint(s, "-") SqueezeAndPrint(s, "r") End Sub End Module
Produce a language-to-language conversion: from Groovy to Go, same semantics.
class StringSqueezable { static void main(String[] args) { String[] testStrings = [ "", "\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln ", "..1111111111111111111111111111111111111111111111111111111111111117777888", "I never give 'em hell, I just tell the truth, and they think it's hell. ", " --- Harry S Truman ", "122333444455555666666777777788888888999999999", "The better the 4-wheel drive, the further you'll be from help when ya get stuck!", "headmistressship" ] String[] testChar = [" ", "-", "7", ".", " -r", "5", "e", "s"] for (int testNum = 0; testNum < testStrings.length; testNum++) { String s = testStrings[testNum] for (char c : testChar[testNum].toCharArray()) { String result = squeeze(s, c) System.out.printf("use: '%c'%nold: %2d <<<%s>>>%nnew: %2d <<<%s>>>%n%n", c, s.length(), s, result.length(), result) } } } private static String squeeze(String input, char include) { StringBuilder sb = new StringBuilder() for (int i = 0; i < input.length(); i++) { if (i == 0 || input.charAt(i - 1) != input.charAt(i) || (input.charAt(i - 1) == input.charAt(i) && input.charAt(i) != include)) { sb.append(input.charAt(i)) } } return sb.toString() } }
package main import "fmt" func squeeze(s string, c rune) (string, int, int) { r := []rune(s) le, del := len(r), 0 for i := le - 2; i >= 0; i-- { if r[i] == c && r[i] == r[i+1] { copy(r[i:], r[i+1:]) del++ } } if del == 0 { return s, le, le } r = r[:le-del] return string(r), le, len(r) } func main() { strings := []string{ "", `"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln `, "..1111111111111111111111111111111111111111111111111111111111111117777888", "I never give 'em hell, I just tell the truth, and they think it's hell. ", " --- Harry S Truman ", "The better the 4-wheel drive, the further you'll be from help when ya get stuck!", "headmistressship", "aardvark", "πŸ˜πŸ˜€πŸ™ŒπŸ’ƒπŸ˜πŸ˜πŸ˜πŸ™Œ", } chars := [][]rune{{' '}, {'-'}, {'7'}, {'.'}, {' ', '-', 'r'}, {'e'}, {'s'}, {'a'}, {'😍'}} for i, s := range strings { for _, c := range chars[i] { ss, olen, slen := squeeze(s, c) fmt.Printf("specified character = %q\n", c) fmt.Printf("originalΒ : length = %2d, string = «««%s»»»\n", olen, s) fmt.Printf("squeezedΒ : length = %2d, string = «««%s»»»\n\n", slen, ss) } } }
Preserve the algorithm and functionality while converting the code from Groovy to Go.
class StringSqueezable { static void main(String[] args) { String[] testStrings = [ "", "\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln ", "..1111111111111111111111111111111111111111111111111111111111111117777888", "I never give 'em hell, I just tell the truth, and they think it's hell. ", " --- Harry S Truman ", "122333444455555666666777777788888888999999999", "The better the 4-wheel drive, the further you'll be from help when ya get stuck!", "headmistressship" ] String[] testChar = [" ", "-", "7", ".", " -r", "5", "e", "s"] for (int testNum = 0; testNum < testStrings.length; testNum++) { String s = testStrings[testNum] for (char c : testChar[testNum].toCharArray()) { String result = squeeze(s, c) System.out.printf("use: '%c'%nold: %2d <<<%s>>>%nnew: %2d <<<%s>>>%n%n", c, s.length(), s, result.length(), result) } } } private static String squeeze(String input, char include) { StringBuilder sb = new StringBuilder() for (int i = 0; i < input.length(); i++) { if (i == 0 || input.charAt(i - 1) != input.charAt(i) || (input.charAt(i - 1) == input.charAt(i) && input.charAt(i) != include)) { sb.append(input.charAt(i)) } } return sb.toString() } }
package main import "fmt" func squeeze(s string, c rune) (string, int, int) { r := []rune(s) le, del := len(r), 0 for i := le - 2; i >= 0; i-- { if r[i] == c && r[i] == r[i+1] { copy(r[i:], r[i+1:]) del++ } } if del == 0 { return s, le, le } r = r[:le-del] return string(r), le, len(r) } func main() { strings := []string{ "", `"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln `, "..1111111111111111111111111111111111111111111111111111111111111117777888", "I never give 'em hell, I just tell the truth, and they think it's hell. ", " --- Harry S Truman ", "The better the 4-wheel drive, the further you'll be from help when ya get stuck!", "headmistressship", "aardvark", "πŸ˜πŸ˜€πŸ™ŒπŸ’ƒπŸ˜πŸ˜πŸ˜πŸ™Œ", } chars := [][]rune{{' '}, {'-'}, {'7'}, {'.'}, {' ', '-', 'r'}, {'e'}, {'s'}, {'a'}, {'😍'}} for i, s := range strings { for _, c := range chars[i] { ss, olen, slen := squeeze(s, c) fmt.Printf("specified character = %q\n", c) fmt.Printf("originalΒ : length = %2d, string = «««%s»»»\n", olen, s) fmt.Printf("squeezedΒ : length = %2d, string = «««%s»»»\n\n", slen, ss) } } }
Can you help me rewrite this code in C instead of Haskell, keeping it the same logically?
import Text.Printf (printf) input :: [(String, Char)] input = [ ("", ' ') , ("The better the 4-wheel drive, the further you'll be from help when ya get stuck!", 'e') , ("headmistressship", 's') , ("\"If I were two-faced, would I be wearing this one?\" , ("..1111111111111111111111111111111111111111111111111111111111111117777888", '7') , ("I never give 'em hell, I just tell the truth, and they think it's hell. ", '.') , (" , ("aardvark", 'a') , ("πŸ˜πŸ˜€πŸ™ŒπŸ’ƒπŸ˜πŸ˜πŸ˜πŸ™Œ", '😍') ] collapse :: Eq a => [a] -> a -> [a] collapse s c = go s where go [] = [] go (x:y:xs) | x == y && x == c = go (y:xs) | otherwise = x : go (y:xs) go xs = xs main :: IO () main = mapM_ (\(a, b, c) -> printf "squeeze: '%c'\nold: %3d «««%s»»»\nnew: %3d «««%s»»»\n\n" c (length a) a (length b) b) $ (\(s, c) -> (s, collapse s c, c)) <$> input
#include<string.h> #include<stdlib.h> #include<stdio.h> #define COLLAPSE 0 #define SQUEEZE 1 typedef struct charList{ char c; struct charList *next; } charList; int strcmpi(char str1[100],char str2[100]){ int len1 = strlen(str1), len2 = strlen(str2), i; if(len1!=len2){ return 1; } else{ for(i=0;i<len1;i++){ if((str1[i]>='A'&&str1[i]<='Z')&&(str2[i]>='a'&&str2[i]<='z')&&(str2[i]-65!=str1[i])) return 1; else if((str2[i]>='A'&&str2[i]<='Z')&&(str1[i]>='a'&&str1[i]<='z')&&(str1[i]-65!=str2[i])) return 1; else if(str1[i]!=str2[i]) return 1; } } return 0; } charList *strToCharList(char* str){ int len = strlen(str),i; charList *list, *iterator, *nextChar; list = (charList*)malloc(sizeof(charList)); list->c = str[0]; list->next = NULL; iterator = list; for(i=1;i<len;i++){ nextChar = (charList*)malloc(sizeof(charList)); nextChar->c = str[i]; nextChar->next = NULL; iterator->next = nextChar; iterator = nextChar; } return list; } char* charListToString(charList* list){ charList* iterator = list; int count = 0,i; char* str; while(iterator!=NULL){ count++; iterator = iterator->next; } str = (char*)malloc((count+1)*sizeof(char)); iterator = list; for(i=0;i<count;i++){ str[i] = iterator->c; iterator = iterator->next; } free(list); str[i] = '\0'; return str; } char* processString(char str[100],int operation, char squeezeChar){ charList *strList = strToCharList(str),*iterator = strList, *scout; if(operation==SQUEEZE){ while(iterator!=NULL){ if(iterator->c==squeezeChar){ scout = iterator->next; while(scout!=NULL && scout->c==squeezeChar){ iterator->next = scout->next; scout->next = NULL; free(scout); scout = iterator->next; } } iterator = iterator->next; } } else{ while(iterator!=NULL && iterator->next!=NULL){ if(iterator->c == (iterator->next)->c){ scout = iterator->next; squeezeChar = iterator->c; while(scout!=NULL && scout->c==squeezeChar){ iterator->next = scout->next; scout->next = NULL; free(scout); scout = iterator->next; } } iterator = iterator->next; } } return charListToString(strList); } void printResults(char originalString[100], char finalString[100], int operation, char squeezeChar){ if(operation==SQUEEZE){ printf("Specified OperationΒ : SQUEEZE\nTarget CharacterΒ : %c",squeezeChar); } else printf("Specified OperationΒ : COLLAPSE"); printf("\nOriginal %c%c%c%s%c%c%c\nLengthΒ : %d",174,174,174,originalString,175,175,175,(int)strlen(originalString)); printf("\nFinal %c%c%c%s%c%c%c\nLengthΒ : %d\n",174,174,174,finalString,175,175,175,(int)strlen(finalString)); } int main(int argc, char** argv){ int operation; char squeezeChar; if(argc<3||argc>4){ printf("UsageΒ : %s <SQUEEZE|COLLAPSE> <String to be processed> <Character to be squeezed, if operation is SQUEEZE>\n",argv[0]); return 0; } if(strcmpi(argv[1],"SQUEEZE")==0 && argc!=4){ scanf("Please enter characted to be squeezedΒ : %c",&squeezeChar); operation = SQUEEZE; } else if(argc==4){ operation = SQUEEZE; squeezeChar = argv[3][0]; } else if(strcmpi(argv[1],"COLLAPSE")==0){ operation = COLLAPSE; } if(strlen(argv[2])<2){ printResults(argv[2],argv[2],operation,squeezeChar); } else{ printResults(argv[2],processString(argv[2],operation,squeezeChar),operation,squeezeChar); } return 0; }
Port the following code from Haskell to C with equivalent syntax and logic.
import Text.Printf (printf) input :: [(String, Char)] input = [ ("", ' ') , ("The better the 4-wheel drive, the further you'll be from help when ya get stuck!", 'e') , ("headmistressship", 's') , ("\"If I were two-faced, would I be wearing this one?\" , ("..1111111111111111111111111111111111111111111111111111111111111117777888", '7') , ("I never give 'em hell, I just tell the truth, and they think it's hell. ", '.') , (" , ("aardvark", 'a') , ("πŸ˜πŸ˜€πŸ™ŒπŸ’ƒπŸ˜πŸ˜πŸ˜πŸ™Œ", '😍') ] collapse :: Eq a => [a] -> a -> [a] collapse s c = go s where go [] = [] go (x:y:xs) | x == y && x == c = go (y:xs) | otherwise = x : go (y:xs) go xs = xs main :: IO () main = mapM_ (\(a, b, c) -> printf "squeeze: '%c'\nold: %3d «««%s»»»\nnew: %3d «««%s»»»\n\n" c (length a) a (length b) b) $ (\(s, c) -> (s, collapse s c, c)) <$> input
#include<string.h> #include<stdlib.h> #include<stdio.h> #define COLLAPSE 0 #define SQUEEZE 1 typedef struct charList{ char c; struct charList *next; } charList; int strcmpi(char str1[100],char str2[100]){ int len1 = strlen(str1), len2 = strlen(str2), i; if(len1!=len2){ return 1; } else{ for(i=0;i<len1;i++){ if((str1[i]>='A'&&str1[i]<='Z')&&(str2[i]>='a'&&str2[i]<='z')&&(str2[i]-65!=str1[i])) return 1; else if((str2[i]>='A'&&str2[i]<='Z')&&(str1[i]>='a'&&str1[i]<='z')&&(str1[i]-65!=str2[i])) return 1; else if(str1[i]!=str2[i]) return 1; } } return 0; } charList *strToCharList(char* str){ int len = strlen(str),i; charList *list, *iterator, *nextChar; list = (charList*)malloc(sizeof(charList)); list->c = str[0]; list->next = NULL; iterator = list; for(i=1;i<len;i++){ nextChar = (charList*)malloc(sizeof(charList)); nextChar->c = str[i]; nextChar->next = NULL; iterator->next = nextChar; iterator = nextChar; } return list; } char* charListToString(charList* list){ charList* iterator = list; int count = 0,i; char* str; while(iterator!=NULL){ count++; iterator = iterator->next; } str = (char*)malloc((count+1)*sizeof(char)); iterator = list; for(i=0;i<count;i++){ str[i] = iterator->c; iterator = iterator->next; } free(list); str[i] = '\0'; return str; } char* processString(char str[100],int operation, char squeezeChar){ charList *strList = strToCharList(str),*iterator = strList, *scout; if(operation==SQUEEZE){ while(iterator!=NULL){ if(iterator->c==squeezeChar){ scout = iterator->next; while(scout!=NULL && scout->c==squeezeChar){ iterator->next = scout->next; scout->next = NULL; free(scout); scout = iterator->next; } } iterator = iterator->next; } } else{ while(iterator!=NULL && iterator->next!=NULL){ if(iterator->c == (iterator->next)->c){ scout = iterator->next; squeezeChar = iterator->c; while(scout!=NULL && scout->c==squeezeChar){ iterator->next = scout->next; scout->next = NULL; free(scout); scout = iterator->next; } } iterator = iterator->next; } } return charListToString(strList); } void printResults(char originalString[100], char finalString[100], int operation, char squeezeChar){ if(operation==SQUEEZE){ printf("Specified OperationΒ : SQUEEZE\nTarget CharacterΒ : %c",squeezeChar); } else printf("Specified OperationΒ : COLLAPSE"); printf("\nOriginal %c%c%c%s%c%c%c\nLengthΒ : %d",174,174,174,originalString,175,175,175,(int)strlen(originalString)); printf("\nFinal %c%c%c%s%c%c%c\nLengthΒ : %d\n",174,174,174,finalString,175,175,175,(int)strlen(finalString)); } int main(int argc, char** argv){ int operation; char squeezeChar; if(argc<3||argc>4){ printf("UsageΒ : %s <SQUEEZE|COLLAPSE> <String to be processed> <Character to be squeezed, if operation is SQUEEZE>\n",argv[0]); return 0; } if(strcmpi(argv[1],"SQUEEZE")==0 && argc!=4){ scanf("Please enter characted to be squeezedΒ : %c",&squeezeChar); operation = SQUEEZE; } else if(argc==4){ operation = SQUEEZE; squeezeChar = argv[3][0]; } else if(strcmpi(argv[1],"COLLAPSE")==0){ operation = COLLAPSE; } if(strlen(argv[2])<2){ printResults(argv[2],argv[2],operation,squeezeChar); } else{ printResults(argv[2],processString(argv[2],operation,squeezeChar),operation,squeezeChar); } return 0; }
Preserve the algorithm and functionality while converting the code from Haskell to C#.
import Text.Printf (printf) input :: [(String, Char)] input = [ ("", ' ') , ("The better the 4-wheel drive, the further you'll be from help when ya get stuck!", 'e') , ("headmistressship", 's') , ("\"If I were two-faced, would I be wearing this one?\" , ("..1111111111111111111111111111111111111111111111111111111111111117777888", '7') , ("I never give 'em hell, I just tell the truth, and they think it's hell. ", '.') , (" , ("aardvark", 'a') , ("πŸ˜πŸ˜€πŸ™ŒπŸ’ƒπŸ˜πŸ˜πŸ˜πŸ™Œ", '😍') ] collapse :: Eq a => [a] -> a -> [a] collapse s c = go s where go [] = [] go (x:y:xs) | x == y && x == c = go (y:xs) | otherwise = x : go (y:xs) go xs = xs main :: IO () main = mapM_ (\(a, b, c) -> printf "squeeze: '%c'\nold: %3d «««%s»»»\nnew: %3d «««%s»»»\n\n" c (length a) a (length b) b) $ (\(s, c) -> (s, collapse s c, c)) <$> input
using System; using static System.Linq.Enumerable; public class Program { static void Main() { SqueezeAndPrint("", ' '); SqueezeAndPrint("\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln ", '-'); SqueezeAndPrint("..1111111111111111111111111111111111111111111111111111111111111117777888", '7'); SqueezeAndPrint("I never give 'em hell, I just tell the truth, and they think it's hell. ", '.'); string s = " --- Harry S Truman "; SqueezeAndPrint(s, ' '); SqueezeAndPrint(s, '-'); SqueezeAndPrint(s, 'r'); } static void SqueezeAndPrint(string s, char c) { Console.WriteLine($"squeeze: '{c}'"); Console.WriteLine($"old: {s.Length} «««{s}»»»"); s = Squeeze(s, c); Console.WriteLine($"new: {s.Length} «««{s}»»»"); } static string Squeeze(string s, char c) => string.IsNullOrEmpty(s) ? "" : s[0] + new string(Range(1, s.Length - 1).Where(i => s[i] != c || s[i] != s[i - 1]).Select(i => s[i]).ToArray()); }
Convert this Haskell block to C#, preserving its control flow and logic.
import Text.Printf (printf) input :: [(String, Char)] input = [ ("", ' ') , ("The better the 4-wheel drive, the further you'll be from help when ya get stuck!", 'e') , ("headmistressship", 's') , ("\"If I were two-faced, would I be wearing this one?\" , ("..1111111111111111111111111111111111111111111111111111111111111117777888", '7') , ("I never give 'em hell, I just tell the truth, and they think it's hell. ", '.') , (" , ("aardvark", 'a') , ("πŸ˜πŸ˜€πŸ™ŒπŸ’ƒπŸ˜πŸ˜πŸ˜πŸ™Œ", '😍') ] collapse :: Eq a => [a] -> a -> [a] collapse s c = go s where go [] = [] go (x:y:xs) | x == y && x == c = go (y:xs) | otherwise = x : go (y:xs) go xs = xs main :: IO () main = mapM_ (\(a, b, c) -> printf "squeeze: '%c'\nold: %3d «««%s»»»\nnew: %3d «««%s»»»\n\n" c (length a) a (length b) b) $ (\(s, c) -> (s, collapse s c, c)) <$> input
using System; using static System.Linq.Enumerable; public class Program { static void Main() { SqueezeAndPrint("", ' '); SqueezeAndPrint("\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln ", '-'); SqueezeAndPrint("..1111111111111111111111111111111111111111111111111111111111111117777888", '7'); SqueezeAndPrint("I never give 'em hell, I just tell the truth, and they think it's hell. ", '.'); string s = " --- Harry S Truman "; SqueezeAndPrint(s, ' '); SqueezeAndPrint(s, '-'); SqueezeAndPrint(s, 'r'); } static void SqueezeAndPrint(string s, char c) { Console.WriteLine($"squeeze: '{c}'"); Console.WriteLine($"old: {s.Length} «««{s}»»»"); s = Squeeze(s, c); Console.WriteLine($"new: {s.Length} «««{s}»»»"); } static string Squeeze(string s, char c) => string.IsNullOrEmpty(s) ? "" : s[0] + new string(Range(1, s.Length - 1).Where(i => s[i] != c || s[i] != s[i - 1]).Select(i => s[i]).ToArray()); }
Convert the following code from Haskell to C++, ensuring the logic remains intact.
import Text.Printf (printf) input :: [(String, Char)] input = [ ("", ' ') , ("The better the 4-wheel drive, the further you'll be from help when ya get stuck!", 'e') , ("headmistressship", 's') , ("\"If I were two-faced, would I be wearing this one?\" , ("..1111111111111111111111111111111111111111111111111111111111111117777888", '7') , ("I never give 'em hell, I just tell the truth, and they think it's hell. ", '.') , (" , ("aardvark", 'a') , ("πŸ˜πŸ˜€πŸ™ŒπŸ’ƒπŸ˜πŸ˜πŸ˜πŸ™Œ", '😍') ] collapse :: Eq a => [a] -> a -> [a] collapse s c = go s where go [] = [] go (x:y:xs) | x == y && x == c = go (y:xs) | otherwise = x : go (y:xs) go xs = xs main :: IO () main = mapM_ (\(a, b, c) -> printf "squeeze: '%c'\nold: %3d «««%s»»»\nnew: %3d «««%s»»»\n\n" c (length a) a (length b) b) $ (\(s, c) -> (s, collapse s c, c)) <$> input
#include <algorithm> #include <string> #include <iostream> template<typename char_type> std::basic_string<char_type> squeeze(std::basic_string<char_type> str, char_type ch) { auto i = std::unique(str.begin(), str.end(), [ch](char_type a, char_type b) { return a == ch && b == ch; }); str.erase(i, str.end()); return str; } void test(const std::string& str, char ch) { std::cout << "character: '" << ch << "'\n"; std::cout << "original: <<<" << str << ">>>, length: " << str.length() << '\n'; std::string squeezed(squeeze(str, ch)); std::cout << "result: <<<" << squeezed << ">>>, length: " << squeezed.length() << '\n'; std::cout << '\n'; } int main(int argc, char** argv) { test("", ' '); test("\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln ", '-'); test("..1111111111111111111111111111111111111111111111111111111111111117777888", '7'); test("I never give 'em hell, I just tell the truth, and they think it's hell. ", '.'); std::string truman(" --- Harry S Truman "); test(truman, ' '); test(truman, '-'); test(truman, 'r'); return 0; }
Generate a C++ translation of this Haskell snippet without changing its computational steps.
import Text.Printf (printf) input :: [(String, Char)] input = [ ("", ' ') , ("The better the 4-wheel drive, the further you'll be from help when ya get stuck!", 'e') , ("headmistressship", 's') , ("\"If I were two-faced, would I be wearing this one?\" , ("..1111111111111111111111111111111111111111111111111111111111111117777888", '7') , ("I never give 'em hell, I just tell the truth, and they think it's hell. ", '.') , (" , ("aardvark", 'a') , ("πŸ˜πŸ˜€πŸ™ŒπŸ’ƒπŸ˜πŸ˜πŸ˜πŸ™Œ", '😍') ] collapse :: Eq a => [a] -> a -> [a] collapse s c = go s where go [] = [] go (x:y:xs) | x == y && x == c = go (y:xs) | otherwise = x : go (y:xs) go xs = xs main :: IO () main = mapM_ (\(a, b, c) -> printf "squeeze: '%c'\nold: %3d «««%s»»»\nnew: %3d «««%s»»»\n\n" c (length a) a (length b) b) $ (\(s, c) -> (s, collapse s c, c)) <$> input
#include <algorithm> #include <string> #include <iostream> template<typename char_type> std::basic_string<char_type> squeeze(std::basic_string<char_type> str, char_type ch) { auto i = std::unique(str.begin(), str.end(), [ch](char_type a, char_type b) { return a == ch && b == ch; }); str.erase(i, str.end()); return str; } void test(const std::string& str, char ch) { std::cout << "character: '" << ch << "'\n"; std::cout << "original: <<<" << str << ">>>, length: " << str.length() << '\n'; std::string squeezed(squeeze(str, ch)); std::cout << "result: <<<" << squeezed << ">>>, length: " << squeezed.length() << '\n'; std::cout << '\n'; } int main(int argc, char** argv) { test("", ' '); test("\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln ", '-'); test("..1111111111111111111111111111111111111111111111111111111111111117777888", '7'); test("I never give 'em hell, I just tell the truth, and they think it's hell. ", '.'); std::string truman(" --- Harry S Truman "); test(truman, ' '); test(truman, '-'); test(truman, 'r'); return 0; }
Change the programming language of this snippet from Haskell to Java without modifying what it does.
import Text.Printf (printf) input :: [(String, Char)] input = [ ("", ' ') , ("The better the 4-wheel drive, the further you'll be from help when ya get stuck!", 'e') , ("headmistressship", 's') , ("\"If I were two-faced, would I be wearing this one?\" , ("..1111111111111111111111111111111111111111111111111111111111111117777888", '7') , ("I never give 'em hell, I just tell the truth, and they think it's hell. ", '.') , (" , ("aardvark", 'a') , ("πŸ˜πŸ˜€πŸ™ŒπŸ’ƒπŸ˜πŸ˜πŸ˜πŸ™Œ", '😍') ] collapse :: Eq a => [a] -> a -> [a] collapse s c = go s where go [] = [] go (x:y:xs) | x == y && x == c = go (y:xs) | otherwise = x : go (y:xs) go xs = xs main :: IO () main = mapM_ (\(a, b, c) -> printf "squeeze: '%c'\nold: %3d «««%s»»»\nnew: %3d «««%s»»»\n\n" c (length a) a (length b) b) $ (\(s, c) -> (s, collapse s c, c)) <$> input
public class StringSqueezable { public static void main(String[] args) { String[] testStrings = new String[] { "", "\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln ", "..1111111111111111111111111111111111111111111111111111111111111117777888", "I never give 'em hell, I just tell the truth, and they think it's hell. ", " --- Harry S Truman ", "122333444455555666666777777788888888999999999", "The better the 4-wheel drive, the further you'll be from help when ya get stuck!", "headmistressship"}; String[] testChar = new String[] { " ", "-", "7", ".", " -r", "5", "e", "s"}; for ( int testNum = 0 ; testNum < testStrings.length ; testNum++ ) { String s = testStrings[testNum]; for ( char c : testChar[testNum].toCharArray() ) { String result = squeeze(s, c); System.out.printf("use: '%c'%nold: %2d <<<%s>>>%nnew: %2d <<<%s>>>%n%n", c, s.length(), s, result.length(), result); } } } private static String squeeze(String in, char include) { StringBuilder sb = new StringBuilder(); for ( int i = 0 ; i < in.length() ; i++ ) { if ( i == 0 || in.charAt(i-1) != in.charAt(i) || (in.charAt(i-1) == in.charAt(i) && in.charAt(i) != include)) { sb.append(in.charAt(i)); } } return sb.toString(); } }
Write the same algorithm in Java as shown in this Haskell implementation.
import Text.Printf (printf) input :: [(String, Char)] input = [ ("", ' ') , ("The better the 4-wheel drive, the further you'll be from help when ya get stuck!", 'e') , ("headmistressship", 's') , ("\"If I were two-faced, would I be wearing this one?\" , ("..1111111111111111111111111111111111111111111111111111111111111117777888", '7') , ("I never give 'em hell, I just tell the truth, and they think it's hell. ", '.') , (" , ("aardvark", 'a') , ("πŸ˜πŸ˜€πŸ™ŒπŸ’ƒπŸ˜πŸ˜πŸ˜πŸ™Œ", '😍') ] collapse :: Eq a => [a] -> a -> [a] collapse s c = go s where go [] = [] go (x:y:xs) | x == y && x == c = go (y:xs) | otherwise = x : go (y:xs) go xs = xs main :: IO () main = mapM_ (\(a, b, c) -> printf "squeeze: '%c'\nold: %3d «««%s»»»\nnew: %3d «««%s»»»\n\n" c (length a) a (length b) b) $ (\(s, c) -> (s, collapse s c, c)) <$> input
public class StringSqueezable { public static void main(String[] args) { String[] testStrings = new String[] { "", "\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln ", "..1111111111111111111111111111111111111111111111111111111111111117777888", "I never give 'em hell, I just tell the truth, and they think it's hell. ", " --- Harry S Truman ", "122333444455555666666777777788888888999999999", "The better the 4-wheel drive, the further you'll be from help when ya get stuck!", "headmistressship"}; String[] testChar = new String[] { " ", "-", "7", ".", " -r", "5", "e", "s"}; for ( int testNum = 0 ; testNum < testStrings.length ; testNum++ ) { String s = testStrings[testNum]; for ( char c : testChar[testNum].toCharArray() ) { String result = squeeze(s, c); System.out.printf("use: '%c'%nold: %2d <<<%s>>>%nnew: %2d <<<%s>>>%n%n", c, s.length(), s, result.length(), result); } } } private static String squeeze(String in, char include) { StringBuilder sb = new StringBuilder(); for ( int i = 0 ; i < in.length() ; i++ ) { if ( i == 0 || in.charAt(i-1) != in.charAt(i) || (in.charAt(i-1) == in.charAt(i) && in.charAt(i) != include)) { sb.append(in.charAt(i)); } } return sb.toString(); } }
Write the same code in Python as shown below in Haskell.
import Text.Printf (printf) input :: [(String, Char)] input = [ ("", ' ') , ("The better the 4-wheel drive, the further you'll be from help when ya get stuck!", 'e') , ("headmistressship", 's') , ("\"If I were two-faced, would I be wearing this one?\" , ("..1111111111111111111111111111111111111111111111111111111111111117777888", '7') , ("I never give 'em hell, I just tell the truth, and they think it's hell. ", '.') , (" , ("aardvark", 'a') , ("πŸ˜πŸ˜€πŸ™ŒπŸ’ƒπŸ˜πŸ˜πŸ˜πŸ™Œ", '😍') ] collapse :: Eq a => [a] -> a -> [a] collapse s c = go s where go [] = [] go (x:y:xs) | x == y && x == c = go (y:xs) | otherwise = x : go (y:xs) go xs = xs main :: IO () main = mapM_ (\(a, b, c) -> printf "squeeze: '%c'\nold: %3d «««%s»»»\nnew: %3d «««%s»»»\n\n" c (length a) a (length b) b) $ (\(s, c) -> (s, collapse s c, c)) <$> input
from itertools import groupby def squeezer(s, txt): return ''.join(item if item == s else ''.join(grp) for item, grp in groupby(txt)) if __name__ == '__main__': strings = [ "", '"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln ', "..1111111111111111111111111111111111111111111111111111111111111117777888", "I never give 'em hell, I just tell the truth, and they think it's hell. ", " --- Harry S Truman ", "The better the 4-wheel drive, the further you'll be from help when ya get stuck!", "headmistressship", "aardvark", "πŸ˜πŸ˜€πŸ™ŒπŸ’ƒπŸ˜πŸ˜πŸ˜πŸ™Œ", ] squeezers = ' ,-,7,., -r,e,s,a,😍'.split(',') for txt, chars in zip(strings, squeezers): this = "Original" print(f"\n{this:14} Size: {len(txt)} «««{txt}»»»" ) for ch in chars: this = f"Squeezer '{ch}'" sqz = squeezer(ch, txt) print(f"{this:>14} Size: {len(sqz)} «««{sqz}»»»" )
Translate this program into Python but keep the logic exactly as in Haskell.
import Text.Printf (printf) input :: [(String, Char)] input = [ ("", ' ') , ("The better the 4-wheel drive, the further you'll be from help when ya get stuck!", 'e') , ("headmistressship", 's') , ("\"If I were two-faced, would I be wearing this one?\" , ("..1111111111111111111111111111111111111111111111111111111111111117777888", '7') , ("I never give 'em hell, I just tell the truth, and they think it's hell. ", '.') , (" , ("aardvark", 'a') , ("πŸ˜πŸ˜€πŸ™ŒπŸ’ƒπŸ˜πŸ˜πŸ˜πŸ™Œ", '😍') ] collapse :: Eq a => [a] -> a -> [a] collapse s c = go s where go [] = [] go (x:y:xs) | x == y && x == c = go (y:xs) | otherwise = x : go (y:xs) go xs = xs main :: IO () main = mapM_ (\(a, b, c) -> printf "squeeze: '%c'\nold: %3d «««%s»»»\nnew: %3d «««%s»»»\n\n" c (length a) a (length b) b) $ (\(s, c) -> (s, collapse s c, c)) <$> input
from itertools import groupby def squeezer(s, txt): return ''.join(item if item == s else ''.join(grp) for item, grp in groupby(txt)) if __name__ == '__main__': strings = [ "", '"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln ', "..1111111111111111111111111111111111111111111111111111111111111117777888", "I never give 'em hell, I just tell the truth, and they think it's hell. ", " --- Harry S Truman ", "The better the 4-wheel drive, the further you'll be from help when ya get stuck!", "headmistressship", "aardvark", "πŸ˜πŸ˜€πŸ™ŒπŸ’ƒπŸ˜πŸ˜πŸ˜πŸ™Œ", ] squeezers = ' ,-,7,., -r,e,s,a,😍'.split(',') for txt, chars in zip(strings, squeezers): this = "Original" print(f"\n{this:14} Size: {len(txt)} «««{txt}»»»" ) for ch in chars: this = f"Squeezer '{ch}'" sqz = squeezer(ch, txt) print(f"{this:>14} Size: {len(sqz)} «««{sqz}»»»" )
Translate this program into VB but keep the logic exactly as in Haskell.
import Text.Printf (printf) input :: [(String, Char)] input = [ ("", ' ') , ("The better the 4-wheel drive, the further you'll be from help when ya get stuck!", 'e') , ("headmistressship", 's') , ("\"If I were two-faced, would I be wearing this one?\" , ("..1111111111111111111111111111111111111111111111111111111111111117777888", '7') , ("I never give 'em hell, I just tell the truth, and they think it's hell. ", '.') , (" , ("aardvark", 'a') , ("πŸ˜πŸ˜€πŸ™ŒπŸ’ƒπŸ˜πŸ˜πŸ˜πŸ™Œ", '😍') ] collapse :: Eq a => [a] -> a -> [a] collapse s c = go s where go [] = [] go (x:y:xs) | x == y && x == c = go (y:xs) | otherwise = x : go (y:xs) go xs = xs main :: IO () main = mapM_ (\(a, b, c) -> printf "squeeze: '%c'\nold: %3d «««%s»»»\nnew: %3d «««%s»»»\n\n" c (length a) a (length b) b) $ (\(s, c) -> (s, collapse s c, c)) <$> input
Imports System.Linq.Enumerable Module Module1 Function Squeeze(s As String, c As Char) As String If String.IsNullOrEmpty(s) Then Return "" End If Return s(0) + New String(Range(1, s.Length - 1).Where(Function(i) s(i) <> c OrElse s(i) <> s(i - 1)).Select(Function(i) s(i)).ToArray()) End Function Sub SqueezeAndPrint(s As String, c As Char) Console.WriteLine("squeeze: Console.WriteLine("old: {0} «««{1}»»»", s.Length, s) s = Squeeze(s, c) Console.WriteLine("new: {0} «««{1}»»»", s.Length, s) End Sub Sub Main() Const QUOTE = """" SqueezeAndPrint("", " ") SqueezeAndPrint(QUOTE & "If I were two-faced, would I be wearing this one?" & QUOTE & " --- Abraham Lincoln ", "-") SqueezeAndPrint("..1111111111111111111111111111111111111111111111111111111111111117777888", "7") SqueezeAndPrint("I never give Dim s = " --- Harry S Truman " SqueezeAndPrint(s, " ") SqueezeAndPrint(s, "-") SqueezeAndPrint(s, "r") End Sub End Module
Write the same code in VB as shown below in Haskell.
import Text.Printf (printf) input :: [(String, Char)] input = [ ("", ' ') , ("The better the 4-wheel drive, the further you'll be from help when ya get stuck!", 'e') , ("headmistressship", 's') , ("\"If I were two-faced, would I be wearing this one?\" , ("..1111111111111111111111111111111111111111111111111111111111111117777888", '7') , ("I never give 'em hell, I just tell the truth, and they think it's hell. ", '.') , (" , ("aardvark", 'a') , ("πŸ˜πŸ˜€πŸ™ŒπŸ’ƒπŸ˜πŸ˜πŸ˜πŸ™Œ", '😍') ] collapse :: Eq a => [a] -> a -> [a] collapse s c = go s where go [] = [] go (x:y:xs) | x == y && x == c = go (y:xs) | otherwise = x : go (y:xs) go xs = xs main :: IO () main = mapM_ (\(a, b, c) -> printf "squeeze: '%c'\nold: %3d «««%s»»»\nnew: %3d «««%s»»»\n\n" c (length a) a (length b) b) $ (\(s, c) -> (s, collapse s c, c)) <$> input
Imports System.Linq.Enumerable Module Module1 Function Squeeze(s As String, c As Char) As String If String.IsNullOrEmpty(s) Then Return "" End If Return s(0) + New String(Range(1, s.Length - 1).Where(Function(i) s(i) <> c OrElse s(i) <> s(i - 1)).Select(Function(i) s(i)).ToArray()) End Function Sub SqueezeAndPrint(s As String, c As Char) Console.WriteLine("squeeze: Console.WriteLine("old: {0} «««{1}»»»", s.Length, s) s = Squeeze(s, c) Console.WriteLine("new: {0} «««{1}»»»", s.Length, s) End Sub Sub Main() Const QUOTE = """" SqueezeAndPrint("", " ") SqueezeAndPrint(QUOTE & "If I were two-faced, would I be wearing this one?" & QUOTE & " --- Abraham Lincoln ", "-") SqueezeAndPrint("..1111111111111111111111111111111111111111111111111111111111111117777888", "7") SqueezeAndPrint("I never give Dim s = " --- Harry S Truman " SqueezeAndPrint(s, " ") SqueezeAndPrint(s, "-") SqueezeAndPrint(s, "r") End Sub End Module
Produce a language-to-language conversion: from Haskell to Go, same semantics.
import Text.Printf (printf) input :: [(String, Char)] input = [ ("", ' ') , ("The better the 4-wheel drive, the further you'll be from help when ya get stuck!", 'e') , ("headmistressship", 's') , ("\"If I were two-faced, would I be wearing this one?\" , ("..1111111111111111111111111111111111111111111111111111111111111117777888", '7') , ("I never give 'em hell, I just tell the truth, and they think it's hell. ", '.') , (" , ("aardvark", 'a') , ("πŸ˜πŸ˜€πŸ™ŒπŸ’ƒπŸ˜πŸ˜πŸ˜πŸ™Œ", '😍') ] collapse :: Eq a => [a] -> a -> [a] collapse s c = go s where go [] = [] go (x:y:xs) | x == y && x == c = go (y:xs) | otherwise = x : go (y:xs) go xs = xs main :: IO () main = mapM_ (\(a, b, c) -> printf "squeeze: '%c'\nold: %3d «««%s»»»\nnew: %3d «««%s»»»\n\n" c (length a) a (length b) b) $ (\(s, c) -> (s, collapse s c, c)) <$> input
package main import "fmt" func squeeze(s string, c rune) (string, int, int) { r := []rune(s) le, del := len(r), 0 for i := le - 2; i >= 0; i-- { if r[i] == c && r[i] == r[i+1] { copy(r[i:], r[i+1:]) del++ } } if del == 0 { return s, le, le } r = r[:le-del] return string(r), le, len(r) } func main() { strings := []string{ "", `"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln `, "..1111111111111111111111111111111111111111111111111111111111111117777888", "I never give 'em hell, I just tell the truth, and they think it's hell. ", " --- Harry S Truman ", "The better the 4-wheel drive, the further you'll be from help when ya get stuck!", "headmistressship", "aardvark", "πŸ˜πŸ˜€πŸ™ŒπŸ’ƒπŸ˜πŸ˜πŸ˜πŸ™Œ", } chars := [][]rune{{' '}, {'-'}, {'7'}, {'.'}, {' ', '-', 'r'}, {'e'}, {'s'}, {'a'}, {'😍'}} for i, s := range strings { for _, c := range chars[i] { ss, olen, slen := squeeze(s, c) fmt.Printf("specified character = %q\n", c) fmt.Printf("originalΒ : length = %2d, string = «««%s»»»\n", olen, s) fmt.Printf("squeezedΒ : length = %2d, string = «««%s»»»\n\n", slen, ss) } } }
Write a version of this Haskell function in Go with identical behavior.
import Text.Printf (printf) input :: [(String, Char)] input = [ ("", ' ') , ("The better the 4-wheel drive, the further you'll be from help when ya get stuck!", 'e') , ("headmistressship", 's') , ("\"If I were two-faced, would I be wearing this one?\" , ("..1111111111111111111111111111111111111111111111111111111111111117777888", '7') , ("I never give 'em hell, I just tell the truth, and they think it's hell. ", '.') , (" , ("aardvark", 'a') , ("πŸ˜πŸ˜€πŸ™ŒπŸ’ƒπŸ˜πŸ˜πŸ˜πŸ™Œ", '😍') ] collapse :: Eq a => [a] -> a -> [a] collapse s c = go s where go [] = [] go (x:y:xs) | x == y && x == c = go (y:xs) | otherwise = x : go (y:xs) go xs = xs main :: IO () main = mapM_ (\(a, b, c) -> printf "squeeze: '%c'\nold: %3d «««%s»»»\nnew: %3d «««%s»»»\n\n" c (length a) a (length b) b) $ (\(s, c) -> (s, collapse s c, c)) <$> input
package main import "fmt" func squeeze(s string, c rune) (string, int, int) { r := []rune(s) le, del := len(r), 0 for i := le - 2; i >= 0; i-- { if r[i] == c && r[i] == r[i+1] { copy(r[i:], r[i+1:]) del++ } } if del == 0 { return s, le, le } r = r[:le-del] return string(r), le, len(r) } func main() { strings := []string{ "", `"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln `, "..1111111111111111111111111111111111111111111111111111111111111117777888", "I never give 'em hell, I just tell the truth, and they think it's hell. ", " --- Harry S Truman ", "The better the 4-wheel drive, the further you'll be from help when ya get stuck!", "headmistressship", "aardvark", "πŸ˜πŸ˜€πŸ™ŒπŸ’ƒπŸ˜πŸ˜πŸ˜πŸ™Œ", } chars := [][]rune{{' '}, {'-'}, {'7'}, {'.'}, {' ', '-', 'r'}, {'e'}, {'s'}, {'a'}, {'😍'}} for i, s := range strings { for _, c := range chars[i] { ss, olen, slen := squeeze(s, c) fmt.Printf("specified character = %q\n", c) fmt.Printf("originalΒ : length = %2d, string = «««%s»»»\n", olen, s) fmt.Printf("squeezedΒ : length = %2d, string = «««%s»»»\n\n", slen, ss) } } }
Convert this J block to C, preserving its control flow and logic.
dlb }.~ (=&' ' (i.) 0:) dtb #~ ([: +./\. ' '&~:) deb #~ ((+.) (1: |. (> </\)))@(' '&~:)
#include<string.h> #include<stdlib.h> #include<stdio.h> #define COLLAPSE 0 #define SQUEEZE 1 typedef struct charList{ char c; struct charList *next; } charList; int strcmpi(char str1[100],char str2[100]){ int len1 = strlen(str1), len2 = strlen(str2), i; if(len1!=len2){ return 1; } else{ for(i=0;i<len1;i++){ if((str1[i]>='A'&&str1[i]<='Z')&&(str2[i]>='a'&&str2[i]<='z')&&(str2[i]-65!=str1[i])) return 1; else if((str2[i]>='A'&&str2[i]<='Z')&&(str1[i]>='a'&&str1[i]<='z')&&(str1[i]-65!=str2[i])) return 1; else if(str1[i]!=str2[i]) return 1; } } return 0; } charList *strToCharList(char* str){ int len = strlen(str),i; charList *list, *iterator, *nextChar; list = (charList*)malloc(sizeof(charList)); list->c = str[0]; list->next = NULL; iterator = list; for(i=1;i<len;i++){ nextChar = (charList*)malloc(sizeof(charList)); nextChar->c = str[i]; nextChar->next = NULL; iterator->next = nextChar; iterator = nextChar; } return list; } char* charListToString(charList* list){ charList* iterator = list; int count = 0,i; char* str; while(iterator!=NULL){ count++; iterator = iterator->next; } str = (char*)malloc((count+1)*sizeof(char)); iterator = list; for(i=0;i<count;i++){ str[i] = iterator->c; iterator = iterator->next; } free(list); str[i] = '\0'; return str; } char* processString(char str[100],int operation, char squeezeChar){ charList *strList = strToCharList(str),*iterator = strList, *scout; if(operation==SQUEEZE){ while(iterator!=NULL){ if(iterator->c==squeezeChar){ scout = iterator->next; while(scout!=NULL && scout->c==squeezeChar){ iterator->next = scout->next; scout->next = NULL; free(scout); scout = iterator->next; } } iterator = iterator->next; } } else{ while(iterator!=NULL && iterator->next!=NULL){ if(iterator->c == (iterator->next)->c){ scout = iterator->next; squeezeChar = iterator->c; while(scout!=NULL && scout->c==squeezeChar){ iterator->next = scout->next; scout->next = NULL; free(scout); scout = iterator->next; } } iterator = iterator->next; } } return charListToString(strList); } void printResults(char originalString[100], char finalString[100], int operation, char squeezeChar){ if(operation==SQUEEZE){ printf("Specified OperationΒ : SQUEEZE\nTarget CharacterΒ : %c",squeezeChar); } else printf("Specified OperationΒ : COLLAPSE"); printf("\nOriginal %c%c%c%s%c%c%c\nLengthΒ : %d",174,174,174,originalString,175,175,175,(int)strlen(originalString)); printf("\nFinal %c%c%c%s%c%c%c\nLengthΒ : %d\n",174,174,174,finalString,175,175,175,(int)strlen(finalString)); } int main(int argc, char** argv){ int operation; char squeezeChar; if(argc<3||argc>4){ printf("UsageΒ : %s <SQUEEZE|COLLAPSE> <String to be processed> <Character to be squeezed, if operation is SQUEEZE>\n",argv[0]); return 0; } if(strcmpi(argv[1],"SQUEEZE")==0 && argc!=4){ scanf("Please enter characted to be squeezedΒ : %c",&squeezeChar); operation = SQUEEZE; } else if(argc==4){ operation = SQUEEZE; squeezeChar = argv[3][0]; } else if(strcmpi(argv[1],"COLLAPSE")==0){ operation = COLLAPSE; } if(strlen(argv[2])<2){ printResults(argv[2],argv[2],operation,squeezeChar); } else{ printResults(argv[2],processString(argv[2],operation,squeezeChar),operation,squeezeChar); } return 0; }
Produce a functionally identical C code for the snippet given in J.
dlb }.~ (=&' ' (i.) 0:) dtb #~ ([: +./\. ' '&~:) deb #~ ((+.) (1: |. (> </\)))@(' '&~:)
#include<string.h> #include<stdlib.h> #include<stdio.h> #define COLLAPSE 0 #define SQUEEZE 1 typedef struct charList{ char c; struct charList *next; } charList; int strcmpi(char str1[100],char str2[100]){ int len1 = strlen(str1), len2 = strlen(str2), i; if(len1!=len2){ return 1; } else{ for(i=0;i<len1;i++){ if((str1[i]>='A'&&str1[i]<='Z')&&(str2[i]>='a'&&str2[i]<='z')&&(str2[i]-65!=str1[i])) return 1; else if((str2[i]>='A'&&str2[i]<='Z')&&(str1[i]>='a'&&str1[i]<='z')&&(str1[i]-65!=str2[i])) return 1; else if(str1[i]!=str2[i]) return 1; } } return 0; } charList *strToCharList(char* str){ int len = strlen(str),i; charList *list, *iterator, *nextChar; list = (charList*)malloc(sizeof(charList)); list->c = str[0]; list->next = NULL; iterator = list; for(i=1;i<len;i++){ nextChar = (charList*)malloc(sizeof(charList)); nextChar->c = str[i]; nextChar->next = NULL; iterator->next = nextChar; iterator = nextChar; } return list; } char* charListToString(charList* list){ charList* iterator = list; int count = 0,i; char* str; while(iterator!=NULL){ count++; iterator = iterator->next; } str = (char*)malloc((count+1)*sizeof(char)); iterator = list; for(i=0;i<count;i++){ str[i] = iterator->c; iterator = iterator->next; } free(list); str[i] = '\0'; return str; } char* processString(char str[100],int operation, char squeezeChar){ charList *strList = strToCharList(str),*iterator = strList, *scout; if(operation==SQUEEZE){ while(iterator!=NULL){ if(iterator->c==squeezeChar){ scout = iterator->next; while(scout!=NULL && scout->c==squeezeChar){ iterator->next = scout->next; scout->next = NULL; free(scout); scout = iterator->next; } } iterator = iterator->next; } } else{ while(iterator!=NULL && iterator->next!=NULL){ if(iterator->c == (iterator->next)->c){ scout = iterator->next; squeezeChar = iterator->c; while(scout!=NULL && scout->c==squeezeChar){ iterator->next = scout->next; scout->next = NULL; free(scout); scout = iterator->next; } } iterator = iterator->next; } } return charListToString(strList); } void printResults(char originalString[100], char finalString[100], int operation, char squeezeChar){ if(operation==SQUEEZE){ printf("Specified OperationΒ : SQUEEZE\nTarget CharacterΒ : %c",squeezeChar); } else printf("Specified OperationΒ : COLLAPSE"); printf("\nOriginal %c%c%c%s%c%c%c\nLengthΒ : %d",174,174,174,originalString,175,175,175,(int)strlen(originalString)); printf("\nFinal %c%c%c%s%c%c%c\nLengthΒ : %d\n",174,174,174,finalString,175,175,175,(int)strlen(finalString)); } int main(int argc, char** argv){ int operation; char squeezeChar; if(argc<3||argc>4){ printf("UsageΒ : %s <SQUEEZE|COLLAPSE> <String to be processed> <Character to be squeezed, if operation is SQUEEZE>\n",argv[0]); return 0; } if(strcmpi(argv[1],"SQUEEZE")==0 && argc!=4){ scanf("Please enter characted to be squeezedΒ : %c",&squeezeChar); operation = SQUEEZE; } else if(argc==4){ operation = SQUEEZE; squeezeChar = argv[3][0]; } else if(strcmpi(argv[1],"COLLAPSE")==0){ operation = COLLAPSE; } if(strlen(argv[2])<2){ printResults(argv[2],argv[2],operation,squeezeChar); } else{ printResults(argv[2],processString(argv[2],operation,squeezeChar),operation,squeezeChar); } return 0; }
Generate a C# translation of this J snippet without changing its computational steps.
dlb }.~ (=&' ' (i.) 0:) dtb #~ ([: +./\. ' '&~:) deb #~ ((+.) (1: |. (> </\)))@(' '&~:)
using System; using static System.Linq.Enumerable; public class Program { static void Main() { SqueezeAndPrint("", ' '); SqueezeAndPrint("\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln ", '-'); SqueezeAndPrint("..1111111111111111111111111111111111111111111111111111111111111117777888", '7'); SqueezeAndPrint("I never give 'em hell, I just tell the truth, and they think it's hell. ", '.'); string s = " --- Harry S Truman "; SqueezeAndPrint(s, ' '); SqueezeAndPrint(s, '-'); SqueezeAndPrint(s, 'r'); } static void SqueezeAndPrint(string s, char c) { Console.WriteLine($"squeeze: '{c}'"); Console.WriteLine($"old: {s.Length} «««{s}»»»"); s = Squeeze(s, c); Console.WriteLine($"new: {s.Length} «««{s}»»»"); } static string Squeeze(string s, char c) => string.IsNullOrEmpty(s) ? "" : s[0] + new string(Range(1, s.Length - 1).Where(i => s[i] != c || s[i] != s[i - 1]).Select(i => s[i]).ToArray()); }
Convert this J snippet to C# and keep its semantics consistent.
dlb }.~ (=&' ' (i.) 0:) dtb #~ ([: +./\. ' '&~:) deb #~ ((+.) (1: |. (> </\)))@(' '&~:)
using System; using static System.Linq.Enumerable; public class Program { static void Main() { SqueezeAndPrint("", ' '); SqueezeAndPrint("\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln ", '-'); SqueezeAndPrint("..1111111111111111111111111111111111111111111111111111111111111117777888", '7'); SqueezeAndPrint("I never give 'em hell, I just tell the truth, and they think it's hell. ", '.'); string s = " --- Harry S Truman "; SqueezeAndPrint(s, ' '); SqueezeAndPrint(s, '-'); SqueezeAndPrint(s, 'r'); } static void SqueezeAndPrint(string s, char c) { Console.WriteLine($"squeeze: '{c}'"); Console.WriteLine($"old: {s.Length} «««{s}»»»"); s = Squeeze(s, c); Console.WriteLine($"new: {s.Length} «««{s}»»»"); } static string Squeeze(string s, char c) => string.IsNullOrEmpty(s) ? "" : s[0] + new string(Range(1, s.Length - 1).Where(i => s[i] != c || s[i] != s[i - 1]).Select(i => s[i]).ToArray()); }
Ensure the translated C++ code behaves exactly like the original J snippet.
dlb }.~ (=&' ' (i.) 0:) dtb #~ ([: +./\. ' '&~:) deb #~ ((+.) (1: |. (> </\)))@(' '&~:)
#include <algorithm> #include <string> #include <iostream> template<typename char_type> std::basic_string<char_type> squeeze(std::basic_string<char_type> str, char_type ch) { auto i = std::unique(str.begin(), str.end(), [ch](char_type a, char_type b) { return a == ch && b == ch; }); str.erase(i, str.end()); return str; } void test(const std::string& str, char ch) { std::cout << "character: '" << ch << "'\n"; std::cout << "original: <<<" << str << ">>>, length: " << str.length() << '\n'; std::string squeezed(squeeze(str, ch)); std::cout << "result: <<<" << squeezed << ">>>, length: " << squeezed.length() << '\n'; std::cout << '\n'; } int main(int argc, char** argv) { test("", ' '); test("\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln ", '-'); test("..1111111111111111111111111111111111111111111111111111111111111117777888", '7'); test("I never give 'em hell, I just tell the truth, and they think it's hell. ", '.'); std::string truman(" --- Harry S Truman "); test(truman, ' '); test(truman, '-'); test(truman, 'r'); return 0; }
Generate a C++ translation of this J snippet without changing its computational steps.
dlb }.~ (=&' ' (i.) 0:) dtb #~ ([: +./\. ' '&~:) deb #~ ((+.) (1: |. (> </\)))@(' '&~:)
#include <algorithm> #include <string> #include <iostream> template<typename char_type> std::basic_string<char_type> squeeze(std::basic_string<char_type> str, char_type ch) { auto i = std::unique(str.begin(), str.end(), [ch](char_type a, char_type b) { return a == ch && b == ch; }); str.erase(i, str.end()); return str; } void test(const std::string& str, char ch) { std::cout << "character: '" << ch << "'\n"; std::cout << "original: <<<" << str << ">>>, length: " << str.length() << '\n'; std::string squeezed(squeeze(str, ch)); std::cout << "result: <<<" << squeezed << ">>>, length: " << squeezed.length() << '\n'; std::cout << '\n'; } int main(int argc, char** argv) { test("", ' '); test("\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln ", '-'); test("..1111111111111111111111111111111111111111111111111111111111111117777888", '7'); test("I never give 'em hell, I just tell the truth, and they think it's hell. ", '.'); std::string truman(" --- Harry S Truman "); test(truman, ' '); test(truman, '-'); test(truman, 'r'); return 0; }
Convert this J block to Java, preserving its control flow and logic.
dlb }.~ (=&' ' (i.) 0:) dtb #~ ([: +./\. ' '&~:) deb #~ ((+.) (1: |. (> </\)))@(' '&~:)
public class StringSqueezable { public static void main(String[] args) { String[] testStrings = new String[] { "", "\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln ", "..1111111111111111111111111111111111111111111111111111111111111117777888", "I never give 'em hell, I just tell the truth, and they think it's hell. ", " --- Harry S Truman ", "122333444455555666666777777788888888999999999", "The better the 4-wheel drive, the further you'll be from help when ya get stuck!", "headmistressship"}; String[] testChar = new String[] { " ", "-", "7", ".", " -r", "5", "e", "s"}; for ( int testNum = 0 ; testNum < testStrings.length ; testNum++ ) { String s = testStrings[testNum]; for ( char c : testChar[testNum].toCharArray() ) { String result = squeeze(s, c); System.out.printf("use: '%c'%nold: %2d <<<%s>>>%nnew: %2d <<<%s>>>%n%n", c, s.length(), s, result.length(), result); } } } private static String squeeze(String in, char include) { StringBuilder sb = new StringBuilder(); for ( int i = 0 ; i < in.length() ; i++ ) { if ( i == 0 || in.charAt(i-1) != in.charAt(i) || (in.charAt(i-1) == in.charAt(i) && in.charAt(i) != include)) { sb.append(in.charAt(i)); } } return sb.toString(); } }
Rewrite this program in Java while keeping its functionality equivalent to the J version.
dlb }.~ (=&' ' (i.) 0:) dtb #~ ([: +./\. ' '&~:) deb #~ ((+.) (1: |. (> </\)))@(' '&~:)
public class StringSqueezable { public static void main(String[] args) { String[] testStrings = new String[] { "", "\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln ", "..1111111111111111111111111111111111111111111111111111111111111117777888", "I never give 'em hell, I just tell the truth, and they think it's hell. ", " --- Harry S Truman ", "122333444455555666666777777788888888999999999", "The better the 4-wheel drive, the further you'll be from help when ya get stuck!", "headmistressship"}; String[] testChar = new String[] { " ", "-", "7", ".", " -r", "5", "e", "s"}; for ( int testNum = 0 ; testNum < testStrings.length ; testNum++ ) { String s = testStrings[testNum]; for ( char c : testChar[testNum].toCharArray() ) { String result = squeeze(s, c); System.out.printf("use: '%c'%nold: %2d <<<%s>>>%nnew: %2d <<<%s>>>%n%n", c, s.length(), s, result.length(), result); } } } private static String squeeze(String in, char include) { StringBuilder sb = new StringBuilder(); for ( int i = 0 ; i < in.length() ; i++ ) { if ( i == 0 || in.charAt(i-1) != in.charAt(i) || (in.charAt(i-1) == in.charAt(i) && in.charAt(i) != include)) { sb.append(in.charAt(i)); } } return sb.toString(); } }
Port the following code from J to Python with equivalent syntax and logic.
dlb }.~ (=&' ' (i.) 0:) dtb #~ ([: +./\. ' '&~:) deb #~ ((+.) (1: |. (> </\)))@(' '&~:)
from itertools import groupby def squeezer(s, txt): return ''.join(item if item == s else ''.join(grp) for item, grp in groupby(txt)) if __name__ == '__main__': strings = [ "", '"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln ', "..1111111111111111111111111111111111111111111111111111111111111117777888", "I never give 'em hell, I just tell the truth, and they think it's hell. ", " --- Harry S Truman ", "The better the 4-wheel drive, the further you'll be from help when ya get stuck!", "headmistressship", "aardvark", "πŸ˜πŸ˜€πŸ™ŒπŸ’ƒπŸ˜πŸ˜πŸ˜πŸ™Œ", ] squeezers = ' ,-,7,., -r,e,s,a,😍'.split(',') for txt, chars in zip(strings, squeezers): this = "Original" print(f"\n{this:14} Size: {len(txt)} «««{txt}»»»" ) for ch in chars: this = f"Squeezer '{ch}'" sqz = squeezer(ch, txt) print(f"{this:>14} Size: {len(sqz)} «««{sqz}»»»" )
Produce a functionally identical Python code for the snippet given in J.
dlb }.~ (=&' ' (i.) 0:) dtb #~ ([: +./\. ' '&~:) deb #~ ((+.) (1: |. (> </\)))@(' '&~:)
from itertools import groupby def squeezer(s, txt): return ''.join(item if item == s else ''.join(grp) for item, grp in groupby(txt)) if __name__ == '__main__': strings = [ "", '"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln ', "..1111111111111111111111111111111111111111111111111111111111111117777888", "I never give 'em hell, I just tell the truth, and they think it's hell. ", " --- Harry S Truman ", "The better the 4-wheel drive, the further you'll be from help when ya get stuck!", "headmistressship", "aardvark", "πŸ˜πŸ˜€πŸ™ŒπŸ’ƒπŸ˜πŸ˜πŸ˜πŸ™Œ", ] squeezers = ' ,-,7,., -r,e,s,a,😍'.split(',') for txt, chars in zip(strings, squeezers): this = "Original" print(f"\n{this:14} Size: {len(txt)} «««{txt}»»»" ) for ch in chars: this = f"Squeezer '{ch}'" sqz = squeezer(ch, txt) print(f"{this:>14} Size: {len(sqz)} «««{sqz}»»»" )
Convert this J block to VB, preserving its control flow and logic.
dlb }.~ (=&' ' (i.) 0:) dtb #~ ([: +./\. ' '&~:) deb #~ ((+.) (1: |. (> </\)))@(' '&~:)
Imports System.Linq.Enumerable Module Module1 Function Squeeze(s As String, c As Char) As String If String.IsNullOrEmpty(s) Then Return "" End If Return s(0) + New String(Range(1, s.Length - 1).Where(Function(i) s(i) <> c OrElse s(i) <> s(i - 1)).Select(Function(i) s(i)).ToArray()) End Function Sub SqueezeAndPrint(s As String, c As Char) Console.WriteLine("squeeze: Console.WriteLine("old: {0} «««{1}»»»", s.Length, s) s = Squeeze(s, c) Console.WriteLine("new: {0} «««{1}»»»", s.Length, s) End Sub Sub Main() Const QUOTE = """" SqueezeAndPrint("", " ") SqueezeAndPrint(QUOTE & "If I were two-faced, would I be wearing this one?" & QUOTE & " --- Abraham Lincoln ", "-") SqueezeAndPrint("..1111111111111111111111111111111111111111111111111111111111111117777888", "7") SqueezeAndPrint("I never give Dim s = " --- Harry S Truman " SqueezeAndPrint(s, " ") SqueezeAndPrint(s, "-") SqueezeAndPrint(s, "r") End Sub End Module
Ensure the translated VB code behaves exactly like the original J snippet.
dlb }.~ (=&' ' (i.) 0:) dtb #~ ([: +./\. ' '&~:) deb #~ ((+.) (1: |. (> </\)))@(' '&~:)
Imports System.Linq.Enumerable Module Module1 Function Squeeze(s As String, c As Char) As String If String.IsNullOrEmpty(s) Then Return "" End If Return s(0) + New String(Range(1, s.Length - 1).Where(Function(i) s(i) <> c OrElse s(i) <> s(i - 1)).Select(Function(i) s(i)).ToArray()) End Function Sub SqueezeAndPrint(s As String, c As Char) Console.WriteLine("squeeze: Console.WriteLine("old: {0} «««{1}»»»", s.Length, s) s = Squeeze(s, c) Console.WriteLine("new: {0} «««{1}»»»", s.Length, s) End Sub Sub Main() Const QUOTE = """" SqueezeAndPrint("", " ") SqueezeAndPrint(QUOTE & "If I were two-faced, would I be wearing this one?" & QUOTE & " --- Abraham Lincoln ", "-") SqueezeAndPrint("..1111111111111111111111111111111111111111111111111111111111111117777888", "7") SqueezeAndPrint("I never give Dim s = " --- Harry S Truman " SqueezeAndPrint(s, " ") SqueezeAndPrint(s, "-") SqueezeAndPrint(s, "r") End Sub End Module
Ensure the translated Go code behaves exactly like the original J snippet.
dlb }.~ (=&' ' (i.) 0:) dtb #~ ([: +./\. ' '&~:) deb #~ ((+.) (1: |. (> </\)))@(' '&~:)
package main import "fmt" func squeeze(s string, c rune) (string, int, int) { r := []rune(s) le, del := len(r), 0 for i := le - 2; i >= 0; i-- { if r[i] == c && r[i] == r[i+1] { copy(r[i:], r[i+1:]) del++ } } if del == 0 { return s, le, le } r = r[:le-del] return string(r), le, len(r) } func main() { strings := []string{ "", `"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln `, "..1111111111111111111111111111111111111111111111111111111111111117777888", "I never give 'em hell, I just tell the truth, and they think it's hell. ", " --- Harry S Truman ", "The better the 4-wheel drive, the further you'll be from help when ya get stuck!", "headmistressship", "aardvark", "πŸ˜πŸ˜€πŸ™ŒπŸ’ƒπŸ˜πŸ˜πŸ˜πŸ™Œ", } chars := [][]rune{{' '}, {'-'}, {'7'}, {'.'}, {' ', '-', 'r'}, {'e'}, {'s'}, {'a'}, {'😍'}} for i, s := range strings { for _, c := range chars[i] { ss, olen, slen := squeeze(s, c) fmt.Printf("specified character = %q\n", c) fmt.Printf("originalΒ : length = %2d, string = «««%s»»»\n", olen, s) fmt.Printf("squeezedΒ : length = %2d, string = «««%s»»»\n\n", slen, ss) } } }
Change the following J code into Go without altering its purpose.
dlb }.~ (=&' ' (i.) 0:) dtb #~ ([: +./\. ' '&~:) deb #~ ((+.) (1: |. (> </\)))@(' '&~:)
package main import "fmt" func squeeze(s string, c rune) (string, int, int) { r := []rune(s) le, del := len(r), 0 for i := le - 2; i >= 0; i-- { if r[i] == c && r[i] == r[i+1] { copy(r[i:], r[i+1:]) del++ } } if del == 0 { return s, le, le } r = r[:le-del] return string(r), le, len(r) } func main() { strings := []string{ "", `"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln `, "..1111111111111111111111111111111111111111111111111111111111111117777888", "I never give 'em hell, I just tell the truth, and they think it's hell. ", " --- Harry S Truman ", "The better the 4-wheel drive, the further you'll be from help when ya get stuck!", "headmistressship", "aardvark", "πŸ˜πŸ˜€πŸ™ŒπŸ’ƒπŸ˜πŸ˜πŸ˜πŸ™Œ", } chars := [][]rune{{' '}, {'-'}, {'7'}, {'.'}, {' ', '-', 'r'}, {'e'}, {'s'}, {'a'}, {'😍'}} for i, s := range strings { for _, c := range chars[i] { ss, olen, slen := squeeze(s, c) fmt.Printf("specified character = %q\n", c) fmt.Printf("originalΒ : length = %2d, string = «««%s»»»\n", olen, s) fmt.Printf("squeezedΒ : length = %2d, string = «««%s»»»\n\n", slen, ss) } } }
Translate the given Julia code snippet into C without altering its behavior.
const teststringpairs = [ ("", ' '), (""""If I were two-faced, would I be wearing this one?" --- Abraham Lincoln """, '-'), ("..1111111111111111111111111111111111111111111111111111111111111117777888", '7'), ("""I never give 'em hell, I just tell the truth, and they think it's hell. """, '.'), (" --- Harry S Truman ", ' '), (" --- Harry S Truman ", '-'), (" --- Harry S Truman ", 'r')] function squeezed(s, c) t = isempty(s) ? "" : s[1:1] for x in s[2:end] if x != t[end] || x != c t *= x end end t end for (s, c) in teststringpairs n, t = length(s), squeezed(s, c) println("«««$s»»» (length $n)\n", s == t ? "is not squeezed, so remains" : "squeezes to", ":\n«««$t»»» (length $(length(t))).\n") end
#include<string.h> #include<stdlib.h> #include<stdio.h> #define COLLAPSE 0 #define SQUEEZE 1 typedef struct charList{ char c; struct charList *next; } charList; int strcmpi(char str1[100],char str2[100]){ int len1 = strlen(str1), len2 = strlen(str2), i; if(len1!=len2){ return 1; } else{ for(i=0;i<len1;i++){ if((str1[i]>='A'&&str1[i]<='Z')&&(str2[i]>='a'&&str2[i]<='z')&&(str2[i]-65!=str1[i])) return 1; else if((str2[i]>='A'&&str2[i]<='Z')&&(str1[i]>='a'&&str1[i]<='z')&&(str1[i]-65!=str2[i])) return 1; else if(str1[i]!=str2[i]) return 1; } } return 0; } charList *strToCharList(char* str){ int len = strlen(str),i; charList *list, *iterator, *nextChar; list = (charList*)malloc(sizeof(charList)); list->c = str[0]; list->next = NULL; iterator = list; for(i=1;i<len;i++){ nextChar = (charList*)malloc(sizeof(charList)); nextChar->c = str[i]; nextChar->next = NULL; iterator->next = nextChar; iterator = nextChar; } return list; } char* charListToString(charList* list){ charList* iterator = list; int count = 0,i; char* str; while(iterator!=NULL){ count++; iterator = iterator->next; } str = (char*)malloc((count+1)*sizeof(char)); iterator = list; for(i=0;i<count;i++){ str[i] = iterator->c; iterator = iterator->next; } free(list); str[i] = '\0'; return str; } char* processString(char str[100],int operation, char squeezeChar){ charList *strList = strToCharList(str),*iterator = strList, *scout; if(operation==SQUEEZE){ while(iterator!=NULL){ if(iterator->c==squeezeChar){ scout = iterator->next; while(scout!=NULL && scout->c==squeezeChar){ iterator->next = scout->next; scout->next = NULL; free(scout); scout = iterator->next; } } iterator = iterator->next; } } else{ while(iterator!=NULL && iterator->next!=NULL){ if(iterator->c == (iterator->next)->c){ scout = iterator->next; squeezeChar = iterator->c; while(scout!=NULL && scout->c==squeezeChar){ iterator->next = scout->next; scout->next = NULL; free(scout); scout = iterator->next; } } iterator = iterator->next; } } return charListToString(strList); } void printResults(char originalString[100], char finalString[100], int operation, char squeezeChar){ if(operation==SQUEEZE){ printf("Specified OperationΒ : SQUEEZE\nTarget CharacterΒ : %c",squeezeChar); } else printf("Specified OperationΒ : COLLAPSE"); printf("\nOriginal %c%c%c%s%c%c%c\nLengthΒ : %d",174,174,174,originalString,175,175,175,(int)strlen(originalString)); printf("\nFinal %c%c%c%s%c%c%c\nLengthΒ : %d\n",174,174,174,finalString,175,175,175,(int)strlen(finalString)); } int main(int argc, char** argv){ int operation; char squeezeChar; if(argc<3||argc>4){ printf("UsageΒ : %s <SQUEEZE|COLLAPSE> <String to be processed> <Character to be squeezed, if operation is SQUEEZE>\n",argv[0]); return 0; } if(strcmpi(argv[1],"SQUEEZE")==0 && argc!=4){ scanf("Please enter characted to be squeezedΒ : %c",&squeezeChar); operation = SQUEEZE; } else if(argc==4){ operation = SQUEEZE; squeezeChar = argv[3][0]; } else if(strcmpi(argv[1],"COLLAPSE")==0){ operation = COLLAPSE; } if(strlen(argv[2])<2){ printResults(argv[2],argv[2],operation,squeezeChar); } else{ printResults(argv[2],processString(argv[2],operation,squeezeChar),operation,squeezeChar); } return 0; }
Translate this program into C but keep the logic exactly as in Julia.
const teststringpairs = [ ("", ' '), (""""If I were two-faced, would I be wearing this one?" --- Abraham Lincoln """, '-'), ("..1111111111111111111111111111111111111111111111111111111111111117777888", '7'), ("""I never give 'em hell, I just tell the truth, and they think it's hell. """, '.'), (" --- Harry S Truman ", ' '), (" --- Harry S Truman ", '-'), (" --- Harry S Truman ", 'r')] function squeezed(s, c) t = isempty(s) ? "" : s[1:1] for x in s[2:end] if x != t[end] || x != c t *= x end end t end for (s, c) in teststringpairs n, t = length(s), squeezed(s, c) println("«««$s»»» (length $n)\n", s == t ? "is not squeezed, so remains" : "squeezes to", ":\n«««$t»»» (length $(length(t))).\n") end
#include<string.h> #include<stdlib.h> #include<stdio.h> #define COLLAPSE 0 #define SQUEEZE 1 typedef struct charList{ char c; struct charList *next; } charList; int strcmpi(char str1[100],char str2[100]){ int len1 = strlen(str1), len2 = strlen(str2), i; if(len1!=len2){ return 1; } else{ for(i=0;i<len1;i++){ if((str1[i]>='A'&&str1[i]<='Z')&&(str2[i]>='a'&&str2[i]<='z')&&(str2[i]-65!=str1[i])) return 1; else if((str2[i]>='A'&&str2[i]<='Z')&&(str1[i]>='a'&&str1[i]<='z')&&(str1[i]-65!=str2[i])) return 1; else if(str1[i]!=str2[i]) return 1; } } return 0; } charList *strToCharList(char* str){ int len = strlen(str),i; charList *list, *iterator, *nextChar; list = (charList*)malloc(sizeof(charList)); list->c = str[0]; list->next = NULL; iterator = list; for(i=1;i<len;i++){ nextChar = (charList*)malloc(sizeof(charList)); nextChar->c = str[i]; nextChar->next = NULL; iterator->next = nextChar; iterator = nextChar; } return list; } char* charListToString(charList* list){ charList* iterator = list; int count = 0,i; char* str; while(iterator!=NULL){ count++; iterator = iterator->next; } str = (char*)malloc((count+1)*sizeof(char)); iterator = list; for(i=0;i<count;i++){ str[i] = iterator->c; iterator = iterator->next; } free(list); str[i] = '\0'; return str; } char* processString(char str[100],int operation, char squeezeChar){ charList *strList = strToCharList(str),*iterator = strList, *scout; if(operation==SQUEEZE){ while(iterator!=NULL){ if(iterator->c==squeezeChar){ scout = iterator->next; while(scout!=NULL && scout->c==squeezeChar){ iterator->next = scout->next; scout->next = NULL; free(scout); scout = iterator->next; } } iterator = iterator->next; } } else{ while(iterator!=NULL && iterator->next!=NULL){ if(iterator->c == (iterator->next)->c){ scout = iterator->next; squeezeChar = iterator->c; while(scout!=NULL && scout->c==squeezeChar){ iterator->next = scout->next; scout->next = NULL; free(scout); scout = iterator->next; } } iterator = iterator->next; } } return charListToString(strList); } void printResults(char originalString[100], char finalString[100], int operation, char squeezeChar){ if(operation==SQUEEZE){ printf("Specified OperationΒ : SQUEEZE\nTarget CharacterΒ : %c",squeezeChar); } else printf("Specified OperationΒ : COLLAPSE"); printf("\nOriginal %c%c%c%s%c%c%c\nLengthΒ : %d",174,174,174,originalString,175,175,175,(int)strlen(originalString)); printf("\nFinal %c%c%c%s%c%c%c\nLengthΒ : %d\n",174,174,174,finalString,175,175,175,(int)strlen(finalString)); } int main(int argc, char** argv){ int operation; char squeezeChar; if(argc<3||argc>4){ printf("UsageΒ : %s <SQUEEZE|COLLAPSE> <String to be processed> <Character to be squeezed, if operation is SQUEEZE>\n",argv[0]); return 0; } if(strcmpi(argv[1],"SQUEEZE")==0 && argc!=4){ scanf("Please enter characted to be squeezedΒ : %c",&squeezeChar); operation = SQUEEZE; } else if(argc==4){ operation = SQUEEZE; squeezeChar = argv[3][0]; } else if(strcmpi(argv[1],"COLLAPSE")==0){ operation = COLLAPSE; } if(strlen(argv[2])<2){ printResults(argv[2],argv[2],operation,squeezeChar); } else{ printResults(argv[2],processString(argv[2],operation,squeezeChar),operation,squeezeChar); } return 0; }
Rewrite the snippet below in C# so it works the same as the original Julia code.
const teststringpairs = [ ("", ' '), (""""If I were two-faced, would I be wearing this one?" --- Abraham Lincoln """, '-'), ("..1111111111111111111111111111111111111111111111111111111111111117777888", '7'), ("""I never give 'em hell, I just tell the truth, and they think it's hell. """, '.'), (" --- Harry S Truman ", ' '), (" --- Harry S Truman ", '-'), (" --- Harry S Truman ", 'r')] function squeezed(s, c) t = isempty(s) ? "" : s[1:1] for x in s[2:end] if x != t[end] || x != c t *= x end end t end for (s, c) in teststringpairs n, t = length(s), squeezed(s, c) println("«««$s»»» (length $n)\n", s == t ? "is not squeezed, so remains" : "squeezes to", ":\n«««$t»»» (length $(length(t))).\n") end
using System; using static System.Linq.Enumerable; public class Program { static void Main() { SqueezeAndPrint("", ' '); SqueezeAndPrint("\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln ", '-'); SqueezeAndPrint("..1111111111111111111111111111111111111111111111111111111111111117777888", '7'); SqueezeAndPrint("I never give 'em hell, I just tell the truth, and they think it's hell. ", '.'); string s = " --- Harry S Truman "; SqueezeAndPrint(s, ' '); SqueezeAndPrint(s, '-'); SqueezeAndPrint(s, 'r'); } static void SqueezeAndPrint(string s, char c) { Console.WriteLine($"squeeze: '{c}'"); Console.WriteLine($"old: {s.Length} «««{s}»»»"); s = Squeeze(s, c); Console.WriteLine($"new: {s.Length} «««{s}»»»"); } static string Squeeze(string s, char c) => string.IsNullOrEmpty(s) ? "" : s[0] + new string(Range(1, s.Length - 1).Where(i => s[i] != c || s[i] != s[i - 1]).Select(i => s[i]).ToArray()); }
Port the following code from Julia to C# with equivalent syntax and logic.
const teststringpairs = [ ("", ' '), (""""If I were two-faced, would I be wearing this one?" --- Abraham Lincoln """, '-'), ("..1111111111111111111111111111111111111111111111111111111111111117777888", '7'), ("""I never give 'em hell, I just tell the truth, and they think it's hell. """, '.'), (" --- Harry S Truman ", ' '), (" --- Harry S Truman ", '-'), (" --- Harry S Truman ", 'r')] function squeezed(s, c) t = isempty(s) ? "" : s[1:1] for x in s[2:end] if x != t[end] || x != c t *= x end end t end for (s, c) in teststringpairs n, t = length(s), squeezed(s, c) println("«««$s»»» (length $n)\n", s == t ? "is not squeezed, so remains" : "squeezes to", ":\n«««$t»»» (length $(length(t))).\n") end
using System; using static System.Linq.Enumerable; public class Program { static void Main() { SqueezeAndPrint("", ' '); SqueezeAndPrint("\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln ", '-'); SqueezeAndPrint("..1111111111111111111111111111111111111111111111111111111111111117777888", '7'); SqueezeAndPrint("I never give 'em hell, I just tell the truth, and they think it's hell. ", '.'); string s = " --- Harry S Truman "; SqueezeAndPrint(s, ' '); SqueezeAndPrint(s, '-'); SqueezeAndPrint(s, 'r'); } static void SqueezeAndPrint(string s, char c) { Console.WriteLine($"squeeze: '{c}'"); Console.WriteLine($"old: {s.Length} «««{s}»»»"); s = Squeeze(s, c); Console.WriteLine($"new: {s.Length} «««{s}»»»"); } static string Squeeze(string s, char c) => string.IsNullOrEmpty(s) ? "" : s[0] + new string(Range(1, s.Length - 1).Where(i => s[i] != c || s[i] != s[i - 1]).Select(i => s[i]).ToArray()); }
Maintain the same structure and functionality when rewriting this code in C++.
const teststringpairs = [ ("", ' '), (""""If I were two-faced, would I be wearing this one?" --- Abraham Lincoln """, '-'), ("..1111111111111111111111111111111111111111111111111111111111111117777888", '7'), ("""I never give 'em hell, I just tell the truth, and they think it's hell. """, '.'), (" --- Harry S Truman ", ' '), (" --- Harry S Truman ", '-'), (" --- Harry S Truman ", 'r')] function squeezed(s, c) t = isempty(s) ? "" : s[1:1] for x in s[2:end] if x != t[end] || x != c t *= x end end t end for (s, c) in teststringpairs n, t = length(s), squeezed(s, c) println("«««$s»»» (length $n)\n", s == t ? "is not squeezed, so remains" : "squeezes to", ":\n«««$t»»» (length $(length(t))).\n") end
#include <algorithm> #include <string> #include <iostream> template<typename char_type> std::basic_string<char_type> squeeze(std::basic_string<char_type> str, char_type ch) { auto i = std::unique(str.begin(), str.end(), [ch](char_type a, char_type b) { return a == ch && b == ch; }); str.erase(i, str.end()); return str; } void test(const std::string& str, char ch) { std::cout << "character: '" << ch << "'\n"; std::cout << "original: <<<" << str << ">>>, length: " << str.length() << '\n'; std::string squeezed(squeeze(str, ch)); std::cout << "result: <<<" << squeezed << ">>>, length: " << squeezed.length() << '\n'; std::cout << '\n'; } int main(int argc, char** argv) { test("", ' '); test("\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln ", '-'); test("..1111111111111111111111111111111111111111111111111111111111111117777888", '7'); test("I never give 'em hell, I just tell the truth, and they think it's hell. ", '.'); std::string truman(" --- Harry S Truman "); test(truman, ' '); test(truman, '-'); test(truman, 'r'); return 0; }
Produce a language-to-language conversion: from Julia to C++, same semantics.
const teststringpairs = [ ("", ' '), (""""If I were two-faced, would I be wearing this one?" --- Abraham Lincoln """, '-'), ("..1111111111111111111111111111111111111111111111111111111111111117777888", '7'), ("""I never give 'em hell, I just tell the truth, and they think it's hell. """, '.'), (" --- Harry S Truman ", ' '), (" --- Harry S Truman ", '-'), (" --- Harry S Truman ", 'r')] function squeezed(s, c) t = isempty(s) ? "" : s[1:1] for x in s[2:end] if x != t[end] || x != c t *= x end end t end for (s, c) in teststringpairs n, t = length(s), squeezed(s, c) println("«««$s»»» (length $n)\n", s == t ? "is not squeezed, so remains" : "squeezes to", ":\n«««$t»»» (length $(length(t))).\n") end
#include <algorithm> #include <string> #include <iostream> template<typename char_type> std::basic_string<char_type> squeeze(std::basic_string<char_type> str, char_type ch) { auto i = std::unique(str.begin(), str.end(), [ch](char_type a, char_type b) { return a == ch && b == ch; }); str.erase(i, str.end()); return str; } void test(const std::string& str, char ch) { std::cout << "character: '" << ch << "'\n"; std::cout << "original: <<<" << str << ">>>, length: " << str.length() << '\n'; std::string squeezed(squeeze(str, ch)); std::cout << "result: <<<" << squeezed << ">>>, length: " << squeezed.length() << '\n'; std::cout << '\n'; } int main(int argc, char** argv) { test("", ' '); test("\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln ", '-'); test("..1111111111111111111111111111111111111111111111111111111111111117777888", '7'); test("I never give 'em hell, I just tell the truth, and they think it's hell. ", '.'); std::string truman(" --- Harry S Truman "); test(truman, ' '); test(truman, '-'); test(truman, 'r'); return 0; }
Keep all operations the same but rewrite the snippet in Java.
const teststringpairs = [ ("", ' '), (""""If I were two-faced, would I be wearing this one?" --- Abraham Lincoln """, '-'), ("..1111111111111111111111111111111111111111111111111111111111111117777888", '7'), ("""I never give 'em hell, I just tell the truth, and they think it's hell. """, '.'), (" --- Harry S Truman ", ' '), (" --- Harry S Truman ", '-'), (" --- Harry S Truman ", 'r')] function squeezed(s, c) t = isempty(s) ? "" : s[1:1] for x in s[2:end] if x != t[end] || x != c t *= x end end t end for (s, c) in teststringpairs n, t = length(s), squeezed(s, c) println("«««$s»»» (length $n)\n", s == t ? "is not squeezed, so remains" : "squeezes to", ":\n«««$t»»» (length $(length(t))).\n") end
public class StringSqueezable { public static void main(String[] args) { String[] testStrings = new String[] { "", "\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln ", "..1111111111111111111111111111111111111111111111111111111111111117777888", "I never give 'em hell, I just tell the truth, and they think it's hell. ", " --- Harry S Truman ", "122333444455555666666777777788888888999999999", "The better the 4-wheel drive, the further you'll be from help when ya get stuck!", "headmistressship"}; String[] testChar = new String[] { " ", "-", "7", ".", " -r", "5", "e", "s"}; for ( int testNum = 0 ; testNum < testStrings.length ; testNum++ ) { String s = testStrings[testNum]; for ( char c : testChar[testNum].toCharArray() ) { String result = squeeze(s, c); System.out.printf("use: '%c'%nold: %2d <<<%s>>>%nnew: %2d <<<%s>>>%n%n", c, s.length(), s, result.length(), result); } } } private static String squeeze(String in, char include) { StringBuilder sb = new StringBuilder(); for ( int i = 0 ; i < in.length() ; i++ ) { if ( i == 0 || in.charAt(i-1) != in.charAt(i) || (in.charAt(i-1) == in.charAt(i) && in.charAt(i) != include)) { sb.append(in.charAt(i)); } } return sb.toString(); } }
Convert this Julia block to Java, preserving its control flow and logic.
const teststringpairs = [ ("", ' '), (""""If I were two-faced, would I be wearing this one?" --- Abraham Lincoln """, '-'), ("..1111111111111111111111111111111111111111111111111111111111111117777888", '7'), ("""I never give 'em hell, I just tell the truth, and they think it's hell. """, '.'), (" --- Harry S Truman ", ' '), (" --- Harry S Truman ", '-'), (" --- Harry S Truman ", 'r')] function squeezed(s, c) t = isempty(s) ? "" : s[1:1] for x in s[2:end] if x != t[end] || x != c t *= x end end t end for (s, c) in teststringpairs n, t = length(s), squeezed(s, c) println("«««$s»»» (length $n)\n", s == t ? "is not squeezed, so remains" : "squeezes to", ":\n«««$t»»» (length $(length(t))).\n") end
public class StringSqueezable { public static void main(String[] args) { String[] testStrings = new String[] { "", "\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln ", "..1111111111111111111111111111111111111111111111111111111111111117777888", "I never give 'em hell, I just tell the truth, and they think it's hell. ", " --- Harry S Truman ", "122333444455555666666777777788888888999999999", "The better the 4-wheel drive, the further you'll be from help when ya get stuck!", "headmistressship"}; String[] testChar = new String[] { " ", "-", "7", ".", " -r", "5", "e", "s"}; for ( int testNum = 0 ; testNum < testStrings.length ; testNum++ ) { String s = testStrings[testNum]; for ( char c : testChar[testNum].toCharArray() ) { String result = squeeze(s, c); System.out.printf("use: '%c'%nold: %2d <<<%s>>>%nnew: %2d <<<%s>>>%n%n", c, s.length(), s, result.length(), result); } } } private static String squeeze(String in, char include) { StringBuilder sb = new StringBuilder(); for ( int i = 0 ; i < in.length() ; i++ ) { if ( i == 0 || in.charAt(i-1) != in.charAt(i) || (in.charAt(i-1) == in.charAt(i) && in.charAt(i) != include)) { sb.append(in.charAt(i)); } } return sb.toString(); } }
Convert this Julia block to Python, preserving its control flow and logic.
const teststringpairs = [ ("", ' '), (""""If I were two-faced, would I be wearing this one?" --- Abraham Lincoln """, '-'), ("..1111111111111111111111111111111111111111111111111111111111111117777888", '7'), ("""I never give 'em hell, I just tell the truth, and they think it's hell. """, '.'), (" --- Harry S Truman ", ' '), (" --- Harry S Truman ", '-'), (" --- Harry S Truman ", 'r')] function squeezed(s, c) t = isempty(s) ? "" : s[1:1] for x in s[2:end] if x != t[end] || x != c t *= x end end t end for (s, c) in teststringpairs n, t = length(s), squeezed(s, c) println("«««$s»»» (length $n)\n", s == t ? "is not squeezed, so remains" : "squeezes to", ":\n«««$t»»» (length $(length(t))).\n") end
from itertools import groupby def squeezer(s, txt): return ''.join(item if item == s else ''.join(grp) for item, grp in groupby(txt)) if __name__ == '__main__': strings = [ "", '"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln ', "..1111111111111111111111111111111111111111111111111111111111111117777888", "I never give 'em hell, I just tell the truth, and they think it's hell. ", " --- Harry S Truman ", "The better the 4-wheel drive, the further you'll be from help when ya get stuck!", "headmistressship", "aardvark", "πŸ˜πŸ˜€πŸ™ŒπŸ’ƒπŸ˜πŸ˜πŸ˜πŸ™Œ", ] squeezers = ' ,-,7,., -r,e,s,a,😍'.split(',') for txt, chars in zip(strings, squeezers): this = "Original" print(f"\n{this:14} Size: {len(txt)} «««{txt}»»»" ) for ch in chars: this = f"Squeezer '{ch}'" sqz = squeezer(ch, txt) print(f"{this:>14} Size: {len(sqz)} «««{sqz}»»»" )
Change the programming language of this snippet from Julia to Python without modifying what it does.
const teststringpairs = [ ("", ' '), (""""If I were two-faced, would I be wearing this one?" --- Abraham Lincoln """, '-'), ("..1111111111111111111111111111111111111111111111111111111111111117777888", '7'), ("""I never give 'em hell, I just tell the truth, and they think it's hell. """, '.'), (" --- Harry S Truman ", ' '), (" --- Harry S Truman ", '-'), (" --- Harry S Truman ", 'r')] function squeezed(s, c) t = isempty(s) ? "" : s[1:1] for x in s[2:end] if x != t[end] || x != c t *= x end end t end for (s, c) in teststringpairs n, t = length(s), squeezed(s, c) println("«««$s»»» (length $n)\n", s == t ? "is not squeezed, so remains" : "squeezes to", ":\n«««$t»»» (length $(length(t))).\n") end
from itertools import groupby def squeezer(s, txt): return ''.join(item if item == s else ''.join(grp) for item, grp in groupby(txt)) if __name__ == '__main__': strings = [ "", '"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln ', "..1111111111111111111111111111111111111111111111111111111111111117777888", "I never give 'em hell, I just tell the truth, and they think it's hell. ", " --- Harry S Truman ", "The better the 4-wheel drive, the further you'll be from help when ya get stuck!", "headmistressship", "aardvark", "πŸ˜πŸ˜€πŸ™ŒπŸ’ƒπŸ˜πŸ˜πŸ˜πŸ™Œ", ] squeezers = ' ,-,7,., -r,e,s,a,😍'.split(',') for txt, chars in zip(strings, squeezers): this = "Original" print(f"\n{this:14} Size: {len(txt)} «««{txt}»»»" ) for ch in chars: this = f"Squeezer '{ch}'" sqz = squeezer(ch, txt) print(f"{this:>14} Size: {len(sqz)} «««{sqz}»»»" )
Generate a VB translation of this Julia snippet without changing its computational steps.
const teststringpairs = [ ("", ' '), (""""If I were two-faced, would I be wearing this one?" --- Abraham Lincoln """, '-'), ("..1111111111111111111111111111111111111111111111111111111111111117777888", '7'), ("""I never give 'em hell, I just tell the truth, and they think it's hell. """, '.'), (" --- Harry S Truman ", ' '), (" --- Harry S Truman ", '-'), (" --- Harry S Truman ", 'r')] function squeezed(s, c) t = isempty(s) ? "" : s[1:1] for x in s[2:end] if x != t[end] || x != c t *= x end end t end for (s, c) in teststringpairs n, t = length(s), squeezed(s, c) println("«««$s»»» (length $n)\n", s == t ? "is not squeezed, so remains" : "squeezes to", ":\n«««$t»»» (length $(length(t))).\n") end
Imports System.Linq.Enumerable Module Module1 Function Squeeze(s As String, c As Char) As String If String.IsNullOrEmpty(s) Then Return "" End If Return s(0) + New String(Range(1, s.Length - 1).Where(Function(i) s(i) <> c OrElse s(i) <> s(i - 1)).Select(Function(i) s(i)).ToArray()) End Function Sub SqueezeAndPrint(s As String, c As Char) Console.WriteLine("squeeze: Console.WriteLine("old: {0} «««{1}»»»", s.Length, s) s = Squeeze(s, c) Console.WriteLine("new: {0} «««{1}»»»", s.Length, s) End Sub Sub Main() Const QUOTE = """" SqueezeAndPrint("", " ") SqueezeAndPrint(QUOTE & "If I were two-faced, would I be wearing this one?" & QUOTE & " --- Abraham Lincoln ", "-") SqueezeAndPrint("..1111111111111111111111111111111111111111111111111111111111111117777888", "7") SqueezeAndPrint("I never give Dim s = " --- Harry S Truman " SqueezeAndPrint(s, " ") SqueezeAndPrint(s, "-") SqueezeAndPrint(s, "r") End Sub End Module
Preserve the algorithm and functionality while converting the code from Julia to VB.
const teststringpairs = [ ("", ' '), (""""If I were two-faced, would I be wearing this one?" --- Abraham Lincoln """, '-'), ("..1111111111111111111111111111111111111111111111111111111111111117777888", '7'), ("""I never give 'em hell, I just tell the truth, and they think it's hell. """, '.'), (" --- Harry S Truman ", ' '), (" --- Harry S Truman ", '-'), (" --- Harry S Truman ", 'r')] function squeezed(s, c) t = isempty(s) ? "" : s[1:1] for x in s[2:end] if x != t[end] || x != c t *= x end end t end for (s, c) in teststringpairs n, t = length(s), squeezed(s, c) println("«««$s»»» (length $n)\n", s == t ? "is not squeezed, so remains" : "squeezes to", ":\n«««$t»»» (length $(length(t))).\n") end
Imports System.Linq.Enumerable Module Module1 Function Squeeze(s As String, c As Char) As String If String.IsNullOrEmpty(s) Then Return "" End If Return s(0) + New String(Range(1, s.Length - 1).Where(Function(i) s(i) <> c OrElse s(i) <> s(i - 1)).Select(Function(i) s(i)).ToArray()) End Function Sub SqueezeAndPrint(s As String, c As Char) Console.WriteLine("squeeze: Console.WriteLine("old: {0} «««{1}»»»", s.Length, s) s = Squeeze(s, c) Console.WriteLine("new: {0} «««{1}»»»", s.Length, s) End Sub Sub Main() Const QUOTE = """" SqueezeAndPrint("", " ") SqueezeAndPrint(QUOTE & "If I were two-faced, would I be wearing this one?" & QUOTE & " --- Abraham Lincoln ", "-") SqueezeAndPrint("..1111111111111111111111111111111111111111111111111111111111111117777888", "7") SqueezeAndPrint("I never give Dim s = " --- Harry S Truman " SqueezeAndPrint(s, " ") SqueezeAndPrint(s, "-") SqueezeAndPrint(s, "r") End Sub End Module
Preserve the algorithm and functionality while converting the code from Julia to Go.
const teststringpairs = [ ("", ' '), (""""If I were two-faced, would I be wearing this one?" --- Abraham Lincoln """, '-'), ("..1111111111111111111111111111111111111111111111111111111111111117777888", '7'), ("""I never give 'em hell, I just tell the truth, and they think it's hell. """, '.'), (" --- Harry S Truman ", ' '), (" --- Harry S Truman ", '-'), (" --- Harry S Truman ", 'r')] function squeezed(s, c) t = isempty(s) ? "" : s[1:1] for x in s[2:end] if x != t[end] || x != c t *= x end end t end for (s, c) in teststringpairs n, t = length(s), squeezed(s, c) println("«««$s»»» (length $n)\n", s == t ? "is not squeezed, so remains" : "squeezes to", ":\n«««$t»»» (length $(length(t))).\n") end
package main import "fmt" func squeeze(s string, c rune) (string, int, int) { r := []rune(s) le, del := len(r), 0 for i := le - 2; i >= 0; i-- { if r[i] == c && r[i] == r[i+1] { copy(r[i:], r[i+1:]) del++ } } if del == 0 { return s, le, le } r = r[:le-del] return string(r), le, len(r) } func main() { strings := []string{ "", `"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln `, "..1111111111111111111111111111111111111111111111111111111111111117777888", "I never give 'em hell, I just tell the truth, and they think it's hell. ", " --- Harry S Truman ", "The better the 4-wheel drive, the further you'll be from help when ya get stuck!", "headmistressship", "aardvark", "πŸ˜πŸ˜€πŸ™ŒπŸ’ƒπŸ˜πŸ˜πŸ˜πŸ™Œ", } chars := [][]rune{{' '}, {'-'}, {'7'}, {'.'}, {' ', '-', 'r'}, {'e'}, {'s'}, {'a'}, {'😍'}} for i, s := range strings { for _, c := range chars[i] { ss, olen, slen := squeeze(s, c) fmt.Printf("specified character = %q\n", c) fmt.Printf("originalΒ : length = %2d, string = «««%s»»»\n", olen, s) fmt.Printf("squeezedΒ : length = %2d, string = «««%s»»»\n\n", slen, ss) } } }
Write a version of this Julia function in Go with identical behavior.
const teststringpairs = [ ("", ' '), (""""If I were two-faced, would I be wearing this one?" --- Abraham Lincoln """, '-'), ("..1111111111111111111111111111111111111111111111111111111111111117777888", '7'), ("""I never give 'em hell, I just tell the truth, and they think it's hell. """, '.'), (" --- Harry S Truman ", ' '), (" --- Harry S Truman ", '-'), (" --- Harry S Truman ", 'r')] function squeezed(s, c) t = isempty(s) ? "" : s[1:1] for x in s[2:end] if x != t[end] || x != c t *= x end end t end for (s, c) in teststringpairs n, t = length(s), squeezed(s, c) println("«««$s»»» (length $n)\n", s == t ? "is not squeezed, so remains" : "squeezes to", ":\n«««$t»»» (length $(length(t))).\n") end
package main import "fmt" func squeeze(s string, c rune) (string, int, int) { r := []rune(s) le, del := len(r), 0 for i := le - 2; i >= 0; i-- { if r[i] == c && r[i] == r[i+1] { copy(r[i:], r[i+1:]) del++ } } if del == 0 { return s, le, le } r = r[:le-del] return string(r), le, len(r) } func main() { strings := []string{ "", `"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln `, "..1111111111111111111111111111111111111111111111111111111111111117777888", "I never give 'em hell, I just tell the truth, and they think it's hell. ", " --- Harry S Truman ", "The better the 4-wheel drive, the further you'll be from help when ya get stuck!", "headmistressship", "aardvark", "πŸ˜πŸ˜€πŸ™ŒπŸ’ƒπŸ˜πŸ˜πŸ˜πŸ™Œ", } chars := [][]rune{{' '}, {'-'}, {'7'}, {'.'}, {' ', '-', 'r'}, {'e'}, {'s'}, {'a'}, {'😍'}} for i, s := range strings { for _, c := range chars[i] { ss, olen, slen := squeeze(s, c) fmt.Printf("specified character = %q\n", c) fmt.Printf("originalΒ : length = %2d, string = «««%s»»»\n", olen, s) fmt.Printf("squeezedΒ : length = %2d, string = «««%s»»»\n\n", slen, ss) } } }
Rewrite this program in C while keeping its functionality equivalent to the Lua version.
function squeezable(s, rune) print("squeeze: `" .. rune .. "`") print("old: <<<" .. s .. ">>>, length = " .. string.len(s)) local last = nil local le = 0 io.write("new: <<<") for c in s:gmatch"." do if c ~= last or c ~= rune then io.write(c) le = le + 1 end last = c end print(">>>, length = " .. le) print() end function main() squeezable("", ' '); squeezable("\"If I were two-faced, would I be wearing this one?\" squeezable("..1111111111111111111111111111111111111111111111111111111111111117777888", '7') squeezable("I never give 'em hell, I just tell the truth, and they think it's hell. ", '.') local s = " squeezable(s, ' ') squeezable(s, '-') squeezable(s, 'r') end main()
#include<string.h> #include<stdlib.h> #include<stdio.h> #define COLLAPSE 0 #define SQUEEZE 1 typedef struct charList{ char c; struct charList *next; } charList; int strcmpi(char str1[100],char str2[100]){ int len1 = strlen(str1), len2 = strlen(str2), i; if(len1!=len2){ return 1; } else{ for(i=0;i<len1;i++){ if((str1[i]>='A'&&str1[i]<='Z')&&(str2[i]>='a'&&str2[i]<='z')&&(str2[i]-65!=str1[i])) return 1; else if((str2[i]>='A'&&str2[i]<='Z')&&(str1[i]>='a'&&str1[i]<='z')&&(str1[i]-65!=str2[i])) return 1; else if(str1[i]!=str2[i]) return 1; } } return 0; } charList *strToCharList(char* str){ int len = strlen(str),i; charList *list, *iterator, *nextChar; list = (charList*)malloc(sizeof(charList)); list->c = str[0]; list->next = NULL; iterator = list; for(i=1;i<len;i++){ nextChar = (charList*)malloc(sizeof(charList)); nextChar->c = str[i]; nextChar->next = NULL; iterator->next = nextChar; iterator = nextChar; } return list; } char* charListToString(charList* list){ charList* iterator = list; int count = 0,i; char* str; while(iterator!=NULL){ count++; iterator = iterator->next; } str = (char*)malloc((count+1)*sizeof(char)); iterator = list; for(i=0;i<count;i++){ str[i] = iterator->c; iterator = iterator->next; } free(list); str[i] = '\0'; return str; } char* processString(char str[100],int operation, char squeezeChar){ charList *strList = strToCharList(str),*iterator = strList, *scout; if(operation==SQUEEZE){ while(iterator!=NULL){ if(iterator->c==squeezeChar){ scout = iterator->next; while(scout!=NULL && scout->c==squeezeChar){ iterator->next = scout->next; scout->next = NULL; free(scout); scout = iterator->next; } } iterator = iterator->next; } } else{ while(iterator!=NULL && iterator->next!=NULL){ if(iterator->c == (iterator->next)->c){ scout = iterator->next; squeezeChar = iterator->c; while(scout!=NULL && scout->c==squeezeChar){ iterator->next = scout->next; scout->next = NULL; free(scout); scout = iterator->next; } } iterator = iterator->next; } } return charListToString(strList); } void printResults(char originalString[100], char finalString[100], int operation, char squeezeChar){ if(operation==SQUEEZE){ printf("Specified OperationΒ : SQUEEZE\nTarget CharacterΒ : %c",squeezeChar); } else printf("Specified OperationΒ : COLLAPSE"); printf("\nOriginal %c%c%c%s%c%c%c\nLengthΒ : %d",174,174,174,originalString,175,175,175,(int)strlen(originalString)); printf("\nFinal %c%c%c%s%c%c%c\nLengthΒ : %d\n",174,174,174,finalString,175,175,175,(int)strlen(finalString)); } int main(int argc, char** argv){ int operation; char squeezeChar; if(argc<3||argc>4){ printf("UsageΒ : %s <SQUEEZE|COLLAPSE> <String to be processed> <Character to be squeezed, if operation is SQUEEZE>\n",argv[0]); return 0; } if(strcmpi(argv[1],"SQUEEZE")==0 && argc!=4){ scanf("Please enter characted to be squeezedΒ : %c",&squeezeChar); operation = SQUEEZE; } else if(argc==4){ operation = SQUEEZE; squeezeChar = argv[3][0]; } else if(strcmpi(argv[1],"COLLAPSE")==0){ operation = COLLAPSE; } if(strlen(argv[2])<2){ printResults(argv[2],argv[2],operation,squeezeChar); } else{ printResults(argv[2],processString(argv[2],operation,squeezeChar),operation,squeezeChar); } return 0; }
Port the provided Lua code into C while preserving the original functionality.
function squeezable(s, rune) print("squeeze: `" .. rune .. "`") print("old: <<<" .. s .. ">>>, length = " .. string.len(s)) local last = nil local le = 0 io.write("new: <<<") for c in s:gmatch"." do if c ~= last or c ~= rune then io.write(c) le = le + 1 end last = c end print(">>>, length = " .. le) print() end function main() squeezable("", ' '); squeezable("\"If I were two-faced, would I be wearing this one?\" squeezable("..1111111111111111111111111111111111111111111111111111111111111117777888", '7') squeezable("I never give 'em hell, I just tell the truth, and they think it's hell. ", '.') local s = " squeezable(s, ' ') squeezable(s, '-') squeezable(s, 'r') end main()
#include<string.h> #include<stdlib.h> #include<stdio.h> #define COLLAPSE 0 #define SQUEEZE 1 typedef struct charList{ char c; struct charList *next; } charList; int strcmpi(char str1[100],char str2[100]){ int len1 = strlen(str1), len2 = strlen(str2), i; if(len1!=len2){ return 1; } else{ for(i=0;i<len1;i++){ if((str1[i]>='A'&&str1[i]<='Z')&&(str2[i]>='a'&&str2[i]<='z')&&(str2[i]-65!=str1[i])) return 1; else if((str2[i]>='A'&&str2[i]<='Z')&&(str1[i]>='a'&&str1[i]<='z')&&(str1[i]-65!=str2[i])) return 1; else if(str1[i]!=str2[i]) return 1; } } return 0; } charList *strToCharList(char* str){ int len = strlen(str),i; charList *list, *iterator, *nextChar; list = (charList*)malloc(sizeof(charList)); list->c = str[0]; list->next = NULL; iterator = list; for(i=1;i<len;i++){ nextChar = (charList*)malloc(sizeof(charList)); nextChar->c = str[i]; nextChar->next = NULL; iterator->next = nextChar; iterator = nextChar; } return list; } char* charListToString(charList* list){ charList* iterator = list; int count = 0,i; char* str; while(iterator!=NULL){ count++; iterator = iterator->next; } str = (char*)malloc((count+1)*sizeof(char)); iterator = list; for(i=0;i<count;i++){ str[i] = iterator->c; iterator = iterator->next; } free(list); str[i] = '\0'; return str; } char* processString(char str[100],int operation, char squeezeChar){ charList *strList = strToCharList(str),*iterator = strList, *scout; if(operation==SQUEEZE){ while(iterator!=NULL){ if(iterator->c==squeezeChar){ scout = iterator->next; while(scout!=NULL && scout->c==squeezeChar){ iterator->next = scout->next; scout->next = NULL; free(scout); scout = iterator->next; } } iterator = iterator->next; } } else{ while(iterator!=NULL && iterator->next!=NULL){ if(iterator->c == (iterator->next)->c){ scout = iterator->next; squeezeChar = iterator->c; while(scout!=NULL && scout->c==squeezeChar){ iterator->next = scout->next; scout->next = NULL; free(scout); scout = iterator->next; } } iterator = iterator->next; } } return charListToString(strList); } void printResults(char originalString[100], char finalString[100], int operation, char squeezeChar){ if(operation==SQUEEZE){ printf("Specified OperationΒ : SQUEEZE\nTarget CharacterΒ : %c",squeezeChar); } else printf("Specified OperationΒ : COLLAPSE"); printf("\nOriginal %c%c%c%s%c%c%c\nLengthΒ : %d",174,174,174,originalString,175,175,175,(int)strlen(originalString)); printf("\nFinal %c%c%c%s%c%c%c\nLengthΒ : %d\n",174,174,174,finalString,175,175,175,(int)strlen(finalString)); } int main(int argc, char** argv){ int operation; char squeezeChar; if(argc<3||argc>4){ printf("UsageΒ : %s <SQUEEZE|COLLAPSE> <String to be processed> <Character to be squeezed, if operation is SQUEEZE>\n",argv[0]); return 0; } if(strcmpi(argv[1],"SQUEEZE")==0 && argc!=4){ scanf("Please enter characted to be squeezedΒ : %c",&squeezeChar); operation = SQUEEZE; } else if(argc==4){ operation = SQUEEZE; squeezeChar = argv[3][0]; } else if(strcmpi(argv[1],"COLLAPSE")==0){ operation = COLLAPSE; } if(strlen(argv[2])<2){ printResults(argv[2],argv[2],operation,squeezeChar); } else{ printResults(argv[2],processString(argv[2],operation,squeezeChar),operation,squeezeChar); } return 0; }
Translate this program into C# but keep the logic exactly as in Lua.
function squeezable(s, rune) print("squeeze: `" .. rune .. "`") print("old: <<<" .. s .. ">>>, length = " .. string.len(s)) local last = nil local le = 0 io.write("new: <<<") for c in s:gmatch"." do if c ~= last or c ~= rune then io.write(c) le = le + 1 end last = c end print(">>>, length = " .. le) print() end function main() squeezable("", ' '); squeezable("\"If I were two-faced, would I be wearing this one?\" squeezable("..1111111111111111111111111111111111111111111111111111111111111117777888", '7') squeezable("I never give 'em hell, I just tell the truth, and they think it's hell. ", '.') local s = " squeezable(s, ' ') squeezable(s, '-') squeezable(s, 'r') end main()
using System; using static System.Linq.Enumerable; public class Program { static void Main() { SqueezeAndPrint("", ' '); SqueezeAndPrint("\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln ", '-'); SqueezeAndPrint("..1111111111111111111111111111111111111111111111111111111111111117777888", '7'); SqueezeAndPrint("I never give 'em hell, I just tell the truth, and they think it's hell. ", '.'); string s = " --- Harry S Truman "; SqueezeAndPrint(s, ' '); SqueezeAndPrint(s, '-'); SqueezeAndPrint(s, 'r'); } static void SqueezeAndPrint(string s, char c) { Console.WriteLine($"squeeze: '{c}'"); Console.WriteLine($"old: {s.Length} «««{s}»»»"); s = Squeeze(s, c); Console.WriteLine($"new: {s.Length} «««{s}»»»"); } static string Squeeze(string s, char c) => string.IsNullOrEmpty(s) ? "" : s[0] + new string(Range(1, s.Length - 1).Where(i => s[i] != c || s[i] != s[i - 1]).Select(i => s[i]).ToArray()); }
Write the same algorithm in C# as shown in this Lua implementation.
function squeezable(s, rune) print("squeeze: `" .. rune .. "`") print("old: <<<" .. s .. ">>>, length = " .. string.len(s)) local last = nil local le = 0 io.write("new: <<<") for c in s:gmatch"." do if c ~= last or c ~= rune then io.write(c) le = le + 1 end last = c end print(">>>, length = " .. le) print() end function main() squeezable("", ' '); squeezable("\"If I were two-faced, would I be wearing this one?\" squeezable("..1111111111111111111111111111111111111111111111111111111111111117777888", '7') squeezable("I never give 'em hell, I just tell the truth, and they think it's hell. ", '.') local s = " squeezable(s, ' ') squeezable(s, '-') squeezable(s, 'r') end main()
using System; using static System.Linq.Enumerable; public class Program { static void Main() { SqueezeAndPrint("", ' '); SqueezeAndPrint("\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln ", '-'); SqueezeAndPrint("..1111111111111111111111111111111111111111111111111111111111111117777888", '7'); SqueezeAndPrint("I never give 'em hell, I just tell the truth, and they think it's hell. ", '.'); string s = " --- Harry S Truman "; SqueezeAndPrint(s, ' '); SqueezeAndPrint(s, '-'); SqueezeAndPrint(s, 'r'); } static void SqueezeAndPrint(string s, char c) { Console.WriteLine($"squeeze: '{c}'"); Console.WriteLine($"old: {s.Length} «««{s}»»»"); s = Squeeze(s, c); Console.WriteLine($"new: {s.Length} «««{s}»»»"); } static string Squeeze(string s, char c) => string.IsNullOrEmpty(s) ? "" : s[0] + new string(Range(1, s.Length - 1).Where(i => s[i] != c || s[i] != s[i - 1]).Select(i => s[i]).ToArray()); }
Change the programming language of this snippet from Lua to C++ without modifying what it does.
function squeezable(s, rune) print("squeeze: `" .. rune .. "`") print("old: <<<" .. s .. ">>>, length = " .. string.len(s)) local last = nil local le = 0 io.write("new: <<<") for c in s:gmatch"." do if c ~= last or c ~= rune then io.write(c) le = le + 1 end last = c end print(">>>, length = " .. le) print() end function main() squeezable("", ' '); squeezable("\"If I were two-faced, would I be wearing this one?\" squeezable("..1111111111111111111111111111111111111111111111111111111111111117777888", '7') squeezable("I never give 'em hell, I just tell the truth, and they think it's hell. ", '.') local s = " squeezable(s, ' ') squeezable(s, '-') squeezable(s, 'r') end main()
#include <algorithm> #include <string> #include <iostream> template<typename char_type> std::basic_string<char_type> squeeze(std::basic_string<char_type> str, char_type ch) { auto i = std::unique(str.begin(), str.end(), [ch](char_type a, char_type b) { return a == ch && b == ch; }); str.erase(i, str.end()); return str; } void test(const std::string& str, char ch) { std::cout << "character: '" << ch << "'\n"; std::cout << "original: <<<" << str << ">>>, length: " << str.length() << '\n'; std::string squeezed(squeeze(str, ch)); std::cout << "result: <<<" << squeezed << ">>>, length: " << squeezed.length() << '\n'; std::cout << '\n'; } int main(int argc, char** argv) { test("", ' '); test("\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln ", '-'); test("..1111111111111111111111111111111111111111111111111111111111111117777888", '7'); test("I never give 'em hell, I just tell the truth, and they think it's hell. ", '.'); std::string truman(" --- Harry S Truman "); test(truman, ' '); test(truman, '-'); test(truman, 'r'); return 0; }
Change the following Lua code into C++ without altering its purpose.
function squeezable(s, rune) print("squeeze: `" .. rune .. "`") print("old: <<<" .. s .. ">>>, length = " .. string.len(s)) local last = nil local le = 0 io.write("new: <<<") for c in s:gmatch"." do if c ~= last or c ~= rune then io.write(c) le = le + 1 end last = c end print(">>>, length = " .. le) print() end function main() squeezable("", ' '); squeezable("\"If I were two-faced, would I be wearing this one?\" squeezable("..1111111111111111111111111111111111111111111111111111111111111117777888", '7') squeezable("I never give 'em hell, I just tell the truth, and they think it's hell. ", '.') local s = " squeezable(s, ' ') squeezable(s, '-') squeezable(s, 'r') end main()
#include <algorithm> #include <string> #include <iostream> template<typename char_type> std::basic_string<char_type> squeeze(std::basic_string<char_type> str, char_type ch) { auto i = std::unique(str.begin(), str.end(), [ch](char_type a, char_type b) { return a == ch && b == ch; }); str.erase(i, str.end()); return str; } void test(const std::string& str, char ch) { std::cout << "character: '" << ch << "'\n"; std::cout << "original: <<<" << str << ">>>, length: " << str.length() << '\n'; std::string squeezed(squeeze(str, ch)); std::cout << "result: <<<" << squeezed << ">>>, length: " << squeezed.length() << '\n'; std::cout << '\n'; } int main(int argc, char** argv) { test("", ' '); test("\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln ", '-'); test("..1111111111111111111111111111111111111111111111111111111111111117777888", '7'); test("I never give 'em hell, I just tell the truth, and they think it's hell. ", '.'); std::string truman(" --- Harry S Truman "); test(truman, ' '); test(truman, '-'); test(truman, 'r'); return 0; }
Change the following Lua code into Java without altering its purpose.
function squeezable(s, rune) print("squeeze: `" .. rune .. "`") print("old: <<<" .. s .. ">>>, length = " .. string.len(s)) local last = nil local le = 0 io.write("new: <<<") for c in s:gmatch"." do if c ~= last or c ~= rune then io.write(c) le = le + 1 end last = c end print(">>>, length = " .. le) print() end function main() squeezable("", ' '); squeezable("\"If I were two-faced, would I be wearing this one?\" squeezable("..1111111111111111111111111111111111111111111111111111111111111117777888", '7') squeezable("I never give 'em hell, I just tell the truth, and they think it's hell. ", '.') local s = " squeezable(s, ' ') squeezable(s, '-') squeezable(s, 'r') end main()
public class StringSqueezable { public static void main(String[] args) { String[] testStrings = new String[] { "", "\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln ", "..1111111111111111111111111111111111111111111111111111111111111117777888", "I never give 'em hell, I just tell the truth, and they think it's hell. ", " --- Harry S Truman ", "122333444455555666666777777788888888999999999", "The better the 4-wheel drive, the further you'll be from help when ya get stuck!", "headmistressship"}; String[] testChar = new String[] { " ", "-", "7", ".", " -r", "5", "e", "s"}; for ( int testNum = 0 ; testNum < testStrings.length ; testNum++ ) { String s = testStrings[testNum]; for ( char c : testChar[testNum].toCharArray() ) { String result = squeeze(s, c); System.out.printf("use: '%c'%nold: %2d <<<%s>>>%nnew: %2d <<<%s>>>%n%n", c, s.length(), s, result.length(), result); } } } private static String squeeze(String in, char include) { StringBuilder sb = new StringBuilder(); for ( int i = 0 ; i < in.length() ; i++ ) { if ( i == 0 || in.charAt(i-1) != in.charAt(i) || (in.charAt(i-1) == in.charAt(i) && in.charAt(i) != include)) { sb.append(in.charAt(i)); } } return sb.toString(); } }
Rewrite this program in Java while keeping its functionality equivalent to the Lua version.
function squeezable(s, rune) print("squeeze: `" .. rune .. "`") print("old: <<<" .. s .. ">>>, length = " .. string.len(s)) local last = nil local le = 0 io.write("new: <<<") for c in s:gmatch"." do if c ~= last or c ~= rune then io.write(c) le = le + 1 end last = c end print(">>>, length = " .. le) print() end function main() squeezable("", ' '); squeezable("\"If I were two-faced, would I be wearing this one?\" squeezable("..1111111111111111111111111111111111111111111111111111111111111117777888", '7') squeezable("I never give 'em hell, I just tell the truth, and they think it's hell. ", '.') local s = " squeezable(s, ' ') squeezable(s, '-') squeezable(s, 'r') end main()
public class StringSqueezable { public static void main(String[] args) { String[] testStrings = new String[] { "", "\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln ", "..1111111111111111111111111111111111111111111111111111111111111117777888", "I never give 'em hell, I just tell the truth, and they think it's hell. ", " --- Harry S Truman ", "122333444455555666666777777788888888999999999", "The better the 4-wheel drive, the further you'll be from help when ya get stuck!", "headmistressship"}; String[] testChar = new String[] { " ", "-", "7", ".", " -r", "5", "e", "s"}; for ( int testNum = 0 ; testNum < testStrings.length ; testNum++ ) { String s = testStrings[testNum]; for ( char c : testChar[testNum].toCharArray() ) { String result = squeeze(s, c); System.out.printf("use: '%c'%nold: %2d <<<%s>>>%nnew: %2d <<<%s>>>%n%n", c, s.length(), s, result.length(), result); } } } private static String squeeze(String in, char include) { StringBuilder sb = new StringBuilder(); for ( int i = 0 ; i < in.length() ; i++ ) { if ( i == 0 || in.charAt(i-1) != in.charAt(i) || (in.charAt(i-1) == in.charAt(i) && in.charAt(i) != include)) { sb.append(in.charAt(i)); } } return sb.toString(); } }
Convert this Lua block to Python, preserving its control flow and logic.
function squeezable(s, rune) print("squeeze: `" .. rune .. "`") print("old: <<<" .. s .. ">>>, length = " .. string.len(s)) local last = nil local le = 0 io.write("new: <<<") for c in s:gmatch"." do if c ~= last or c ~= rune then io.write(c) le = le + 1 end last = c end print(">>>, length = " .. le) print() end function main() squeezable("", ' '); squeezable("\"If I were two-faced, would I be wearing this one?\" squeezable("..1111111111111111111111111111111111111111111111111111111111111117777888", '7') squeezable("I never give 'em hell, I just tell the truth, and they think it's hell. ", '.') local s = " squeezable(s, ' ') squeezable(s, '-') squeezable(s, 'r') end main()
from itertools import groupby def squeezer(s, txt): return ''.join(item if item == s else ''.join(grp) for item, grp in groupby(txt)) if __name__ == '__main__': strings = [ "", '"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln ', "..1111111111111111111111111111111111111111111111111111111111111117777888", "I never give 'em hell, I just tell the truth, and they think it's hell. ", " --- Harry S Truman ", "The better the 4-wheel drive, the further you'll be from help when ya get stuck!", "headmistressship", "aardvark", "πŸ˜πŸ˜€πŸ™ŒπŸ’ƒπŸ˜πŸ˜πŸ˜πŸ™Œ", ] squeezers = ' ,-,7,., -r,e,s,a,😍'.split(',') for txt, chars in zip(strings, squeezers): this = "Original" print(f"\n{this:14} Size: {len(txt)} «««{txt}»»»" ) for ch in chars: this = f"Squeezer '{ch}'" sqz = squeezer(ch, txt) print(f"{this:>14} Size: {len(sqz)} «««{sqz}»»»" )
Generate an equivalent Python version of this Lua code.
function squeezable(s, rune) print("squeeze: `" .. rune .. "`") print("old: <<<" .. s .. ">>>, length = " .. string.len(s)) local last = nil local le = 0 io.write("new: <<<") for c in s:gmatch"." do if c ~= last or c ~= rune then io.write(c) le = le + 1 end last = c end print(">>>, length = " .. le) print() end function main() squeezable("", ' '); squeezable("\"If I were two-faced, would I be wearing this one?\" squeezable("..1111111111111111111111111111111111111111111111111111111111111117777888", '7') squeezable("I never give 'em hell, I just tell the truth, and they think it's hell. ", '.') local s = " squeezable(s, ' ') squeezable(s, '-') squeezable(s, 'r') end main()
from itertools import groupby def squeezer(s, txt): return ''.join(item if item == s else ''.join(grp) for item, grp in groupby(txt)) if __name__ == '__main__': strings = [ "", '"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln ', "..1111111111111111111111111111111111111111111111111111111111111117777888", "I never give 'em hell, I just tell the truth, and they think it's hell. ", " --- Harry S Truman ", "The better the 4-wheel drive, the further you'll be from help when ya get stuck!", "headmistressship", "aardvark", "πŸ˜πŸ˜€πŸ™ŒπŸ’ƒπŸ˜πŸ˜πŸ˜πŸ™Œ", ] squeezers = ' ,-,7,., -r,e,s,a,😍'.split(',') for txt, chars in zip(strings, squeezers): this = "Original" print(f"\n{this:14} Size: {len(txt)} «««{txt}»»»" ) for ch in chars: this = f"Squeezer '{ch}'" sqz = squeezer(ch, txt) print(f"{this:>14} Size: {len(sqz)} «««{sqz}»»»" )
Please provide an equivalent version of this Lua code in VB.
function squeezable(s, rune) print("squeeze: `" .. rune .. "`") print("old: <<<" .. s .. ">>>, length = " .. string.len(s)) local last = nil local le = 0 io.write("new: <<<") for c in s:gmatch"." do if c ~= last or c ~= rune then io.write(c) le = le + 1 end last = c end print(">>>, length = " .. le) print() end function main() squeezable("", ' '); squeezable("\"If I were two-faced, would I be wearing this one?\" squeezable("..1111111111111111111111111111111111111111111111111111111111111117777888", '7') squeezable("I never give 'em hell, I just tell the truth, and they think it's hell. ", '.') local s = " squeezable(s, ' ') squeezable(s, '-') squeezable(s, 'r') end main()
Imports System.Linq.Enumerable Module Module1 Function Squeeze(s As String, c As Char) As String If String.IsNullOrEmpty(s) Then Return "" End If Return s(0) + New String(Range(1, s.Length - 1).Where(Function(i) s(i) <> c OrElse s(i) <> s(i - 1)).Select(Function(i) s(i)).ToArray()) End Function Sub SqueezeAndPrint(s As String, c As Char) Console.WriteLine("squeeze: Console.WriteLine("old: {0} «««{1}»»»", s.Length, s) s = Squeeze(s, c) Console.WriteLine("new: {0} «««{1}»»»", s.Length, s) End Sub Sub Main() Const QUOTE = """" SqueezeAndPrint("", " ") SqueezeAndPrint(QUOTE & "If I were two-faced, would I be wearing this one?" & QUOTE & " --- Abraham Lincoln ", "-") SqueezeAndPrint("..1111111111111111111111111111111111111111111111111111111111111117777888", "7") SqueezeAndPrint("I never give Dim s = " --- Harry S Truman " SqueezeAndPrint(s, " ") SqueezeAndPrint(s, "-") SqueezeAndPrint(s, "r") End Sub End Module
Change the following Lua code into VB without altering its purpose.
function squeezable(s, rune) print("squeeze: `" .. rune .. "`") print("old: <<<" .. s .. ">>>, length = " .. string.len(s)) local last = nil local le = 0 io.write("new: <<<") for c in s:gmatch"." do if c ~= last or c ~= rune then io.write(c) le = le + 1 end last = c end print(">>>, length = " .. le) print() end function main() squeezable("", ' '); squeezable("\"If I were two-faced, would I be wearing this one?\" squeezable("..1111111111111111111111111111111111111111111111111111111111111117777888", '7') squeezable("I never give 'em hell, I just tell the truth, and they think it's hell. ", '.') local s = " squeezable(s, ' ') squeezable(s, '-') squeezable(s, 'r') end main()
Imports System.Linq.Enumerable Module Module1 Function Squeeze(s As String, c As Char) As String If String.IsNullOrEmpty(s) Then Return "" End If Return s(0) + New String(Range(1, s.Length - 1).Where(Function(i) s(i) <> c OrElse s(i) <> s(i - 1)).Select(Function(i) s(i)).ToArray()) End Function Sub SqueezeAndPrint(s As String, c As Char) Console.WriteLine("squeeze: Console.WriteLine("old: {0} «««{1}»»»", s.Length, s) s = Squeeze(s, c) Console.WriteLine("new: {0} «««{1}»»»", s.Length, s) End Sub Sub Main() Const QUOTE = """" SqueezeAndPrint("", " ") SqueezeAndPrint(QUOTE & "If I were two-faced, would I be wearing this one?" & QUOTE & " --- Abraham Lincoln ", "-") SqueezeAndPrint("..1111111111111111111111111111111111111111111111111111111111111117777888", "7") SqueezeAndPrint("I never give Dim s = " --- Harry S Truman " SqueezeAndPrint(s, " ") SqueezeAndPrint(s, "-") SqueezeAndPrint(s, "r") End Sub End Module
Produce a functionally identical Go code for the snippet given in Lua.
function squeezable(s, rune) print("squeeze: `" .. rune .. "`") print("old: <<<" .. s .. ">>>, length = " .. string.len(s)) local last = nil local le = 0 io.write("new: <<<") for c in s:gmatch"." do if c ~= last or c ~= rune then io.write(c) le = le + 1 end last = c end print(">>>, length = " .. le) print() end function main() squeezable("", ' '); squeezable("\"If I were two-faced, would I be wearing this one?\" squeezable("..1111111111111111111111111111111111111111111111111111111111111117777888", '7') squeezable("I never give 'em hell, I just tell the truth, and they think it's hell. ", '.') local s = " squeezable(s, ' ') squeezable(s, '-') squeezable(s, 'r') end main()
package main import "fmt" func squeeze(s string, c rune) (string, int, int) { r := []rune(s) le, del := len(r), 0 for i := le - 2; i >= 0; i-- { if r[i] == c && r[i] == r[i+1] { copy(r[i:], r[i+1:]) del++ } } if del == 0 { return s, le, le } r = r[:le-del] return string(r), le, len(r) } func main() { strings := []string{ "", `"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln `, "..1111111111111111111111111111111111111111111111111111111111111117777888", "I never give 'em hell, I just tell the truth, and they think it's hell. ", " --- Harry S Truman ", "The better the 4-wheel drive, the further you'll be from help when ya get stuck!", "headmistressship", "aardvark", "πŸ˜πŸ˜€πŸ™ŒπŸ’ƒπŸ˜πŸ˜πŸ˜πŸ™Œ", } chars := [][]rune{{' '}, {'-'}, {'7'}, {'.'}, {' ', '-', 'r'}, {'e'}, {'s'}, {'a'}, {'😍'}} for i, s := range strings { for _, c := range chars[i] { ss, olen, slen := squeeze(s, c) fmt.Printf("specified character = %q\n", c) fmt.Printf("originalΒ : length = %2d, string = «««%s»»»\n", olen, s) fmt.Printf("squeezedΒ : length = %2d, string = «««%s»»»\n\n", slen, ss) } } }
Change the following Lua code into Go without altering its purpose.
function squeezable(s, rune) print("squeeze: `" .. rune .. "`") print("old: <<<" .. s .. ">>>, length = " .. string.len(s)) local last = nil local le = 0 io.write("new: <<<") for c in s:gmatch"." do if c ~= last or c ~= rune then io.write(c) le = le + 1 end last = c end print(">>>, length = " .. le) print() end function main() squeezable("", ' '); squeezable("\"If I were two-faced, would I be wearing this one?\" squeezable("..1111111111111111111111111111111111111111111111111111111111111117777888", '7') squeezable("I never give 'em hell, I just tell the truth, and they think it's hell. ", '.') local s = " squeezable(s, ' ') squeezable(s, '-') squeezable(s, 'r') end main()
package main import "fmt" func squeeze(s string, c rune) (string, int, int) { r := []rune(s) le, del := len(r), 0 for i := le - 2; i >= 0; i-- { if r[i] == c && r[i] == r[i+1] { copy(r[i:], r[i+1:]) del++ } } if del == 0 { return s, le, le } r = r[:le-del] return string(r), le, len(r) } func main() { strings := []string{ "", `"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln `, "..1111111111111111111111111111111111111111111111111111111111111117777888", "I never give 'em hell, I just tell the truth, and they think it's hell. ", " --- Harry S Truman ", "The better the 4-wheel drive, the further you'll be from help when ya get stuck!", "headmistressship", "aardvark", "πŸ˜πŸ˜€πŸ™ŒπŸ’ƒπŸ˜πŸ˜πŸ˜πŸ™Œ", } chars := [][]rune{{' '}, {'-'}, {'7'}, {'.'}, {' ', '-', 'r'}, {'e'}, {'s'}, {'a'}, {'😍'}} for i, s := range strings { for _, c := range chars[i] { ss, olen, slen := squeeze(s, c) fmt.Printf("specified character = %q\n", c) fmt.Printf("originalΒ : length = %2d, string = «««%s»»»\n", olen, s) fmt.Printf("squeezedΒ : length = %2d, string = «««%s»»»\n\n", slen, ss) } } }
Port the provided Mathematica code into C while preserving the original functionality.
ClearAll[Squeeze] Squeeze[s_String,sq_String]:=StringReplace[s,x:(sq..):>sq] s={ "", "\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln", "..1111111111111111111111111111111111111111111111111111111111111117777888", "I never give 'em hell, I just tell the truth, and they think it's hell. ", " --- Harry S Truman " }; Squeeze[s[[1]],""] Squeeze[s[[2]],"-"] Squeeze[s[[3]],"7"] Squeeze[s[[4]],"."] Squeeze[s[[5]]," "] Squeeze[s[[5]],"-"] Squeeze[s[[5]],"r"]
#include<string.h> #include<stdlib.h> #include<stdio.h> #define COLLAPSE 0 #define SQUEEZE 1 typedef struct charList{ char c; struct charList *next; } charList; int strcmpi(char str1[100],char str2[100]){ int len1 = strlen(str1), len2 = strlen(str2), i; if(len1!=len2){ return 1; } else{ for(i=0;i<len1;i++){ if((str1[i]>='A'&&str1[i]<='Z')&&(str2[i]>='a'&&str2[i]<='z')&&(str2[i]-65!=str1[i])) return 1; else if((str2[i]>='A'&&str2[i]<='Z')&&(str1[i]>='a'&&str1[i]<='z')&&(str1[i]-65!=str2[i])) return 1; else if(str1[i]!=str2[i]) return 1; } } return 0; } charList *strToCharList(char* str){ int len = strlen(str),i; charList *list, *iterator, *nextChar; list = (charList*)malloc(sizeof(charList)); list->c = str[0]; list->next = NULL; iterator = list; for(i=1;i<len;i++){ nextChar = (charList*)malloc(sizeof(charList)); nextChar->c = str[i]; nextChar->next = NULL; iterator->next = nextChar; iterator = nextChar; } return list; } char* charListToString(charList* list){ charList* iterator = list; int count = 0,i; char* str; while(iterator!=NULL){ count++; iterator = iterator->next; } str = (char*)malloc((count+1)*sizeof(char)); iterator = list; for(i=0;i<count;i++){ str[i] = iterator->c; iterator = iterator->next; } free(list); str[i] = '\0'; return str; } char* processString(char str[100],int operation, char squeezeChar){ charList *strList = strToCharList(str),*iterator = strList, *scout; if(operation==SQUEEZE){ while(iterator!=NULL){ if(iterator->c==squeezeChar){ scout = iterator->next; while(scout!=NULL && scout->c==squeezeChar){ iterator->next = scout->next; scout->next = NULL; free(scout); scout = iterator->next; } } iterator = iterator->next; } } else{ while(iterator!=NULL && iterator->next!=NULL){ if(iterator->c == (iterator->next)->c){ scout = iterator->next; squeezeChar = iterator->c; while(scout!=NULL && scout->c==squeezeChar){ iterator->next = scout->next; scout->next = NULL; free(scout); scout = iterator->next; } } iterator = iterator->next; } } return charListToString(strList); } void printResults(char originalString[100], char finalString[100], int operation, char squeezeChar){ if(operation==SQUEEZE){ printf("Specified OperationΒ : SQUEEZE\nTarget CharacterΒ : %c",squeezeChar); } else printf("Specified OperationΒ : COLLAPSE"); printf("\nOriginal %c%c%c%s%c%c%c\nLengthΒ : %d",174,174,174,originalString,175,175,175,(int)strlen(originalString)); printf("\nFinal %c%c%c%s%c%c%c\nLengthΒ : %d\n",174,174,174,finalString,175,175,175,(int)strlen(finalString)); } int main(int argc, char** argv){ int operation; char squeezeChar; if(argc<3||argc>4){ printf("UsageΒ : %s <SQUEEZE|COLLAPSE> <String to be processed> <Character to be squeezed, if operation is SQUEEZE>\n",argv[0]); return 0; } if(strcmpi(argv[1],"SQUEEZE")==0 && argc!=4){ scanf("Please enter characted to be squeezedΒ : %c",&squeezeChar); operation = SQUEEZE; } else if(argc==4){ operation = SQUEEZE; squeezeChar = argv[3][0]; } else if(strcmpi(argv[1],"COLLAPSE")==0){ operation = COLLAPSE; } if(strlen(argv[2])<2){ printResults(argv[2],argv[2],operation,squeezeChar); } else{ printResults(argv[2],processString(argv[2],operation,squeezeChar),operation,squeezeChar); } return 0; }
Rewrite this program in C while keeping its functionality equivalent to the Mathematica version.
ClearAll[Squeeze] Squeeze[s_String,sq_String]:=StringReplace[s,x:(sq..):>sq] s={ "", "\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln", "..1111111111111111111111111111111111111111111111111111111111111117777888", "I never give 'em hell, I just tell the truth, and they think it's hell. ", " --- Harry S Truman " }; Squeeze[s[[1]],""] Squeeze[s[[2]],"-"] Squeeze[s[[3]],"7"] Squeeze[s[[4]],"."] Squeeze[s[[5]]," "] Squeeze[s[[5]],"-"] Squeeze[s[[5]],"r"]
#include<string.h> #include<stdlib.h> #include<stdio.h> #define COLLAPSE 0 #define SQUEEZE 1 typedef struct charList{ char c; struct charList *next; } charList; int strcmpi(char str1[100],char str2[100]){ int len1 = strlen(str1), len2 = strlen(str2), i; if(len1!=len2){ return 1; } else{ for(i=0;i<len1;i++){ if((str1[i]>='A'&&str1[i]<='Z')&&(str2[i]>='a'&&str2[i]<='z')&&(str2[i]-65!=str1[i])) return 1; else if((str2[i]>='A'&&str2[i]<='Z')&&(str1[i]>='a'&&str1[i]<='z')&&(str1[i]-65!=str2[i])) return 1; else if(str1[i]!=str2[i]) return 1; } } return 0; } charList *strToCharList(char* str){ int len = strlen(str),i; charList *list, *iterator, *nextChar; list = (charList*)malloc(sizeof(charList)); list->c = str[0]; list->next = NULL; iterator = list; for(i=1;i<len;i++){ nextChar = (charList*)malloc(sizeof(charList)); nextChar->c = str[i]; nextChar->next = NULL; iterator->next = nextChar; iterator = nextChar; } return list; } char* charListToString(charList* list){ charList* iterator = list; int count = 0,i; char* str; while(iterator!=NULL){ count++; iterator = iterator->next; } str = (char*)malloc((count+1)*sizeof(char)); iterator = list; for(i=0;i<count;i++){ str[i] = iterator->c; iterator = iterator->next; } free(list); str[i] = '\0'; return str; } char* processString(char str[100],int operation, char squeezeChar){ charList *strList = strToCharList(str),*iterator = strList, *scout; if(operation==SQUEEZE){ while(iterator!=NULL){ if(iterator->c==squeezeChar){ scout = iterator->next; while(scout!=NULL && scout->c==squeezeChar){ iterator->next = scout->next; scout->next = NULL; free(scout); scout = iterator->next; } } iterator = iterator->next; } } else{ while(iterator!=NULL && iterator->next!=NULL){ if(iterator->c == (iterator->next)->c){ scout = iterator->next; squeezeChar = iterator->c; while(scout!=NULL && scout->c==squeezeChar){ iterator->next = scout->next; scout->next = NULL; free(scout); scout = iterator->next; } } iterator = iterator->next; } } return charListToString(strList); } void printResults(char originalString[100], char finalString[100], int operation, char squeezeChar){ if(operation==SQUEEZE){ printf("Specified OperationΒ : SQUEEZE\nTarget CharacterΒ : %c",squeezeChar); } else printf("Specified OperationΒ : COLLAPSE"); printf("\nOriginal %c%c%c%s%c%c%c\nLengthΒ : %d",174,174,174,originalString,175,175,175,(int)strlen(originalString)); printf("\nFinal %c%c%c%s%c%c%c\nLengthΒ : %d\n",174,174,174,finalString,175,175,175,(int)strlen(finalString)); } int main(int argc, char** argv){ int operation; char squeezeChar; if(argc<3||argc>4){ printf("UsageΒ : %s <SQUEEZE|COLLAPSE> <String to be processed> <Character to be squeezed, if operation is SQUEEZE>\n",argv[0]); return 0; } if(strcmpi(argv[1],"SQUEEZE")==0 && argc!=4){ scanf("Please enter characted to be squeezedΒ : %c",&squeezeChar); operation = SQUEEZE; } else if(argc==4){ operation = SQUEEZE; squeezeChar = argv[3][0]; } else if(strcmpi(argv[1],"COLLAPSE")==0){ operation = COLLAPSE; } if(strlen(argv[2])<2){ printResults(argv[2],argv[2],operation,squeezeChar); } else{ printResults(argv[2],processString(argv[2],operation,squeezeChar),operation,squeezeChar); } return 0; }
Write the same algorithm in C# as shown in this Mathematica implementation.
ClearAll[Squeeze] Squeeze[s_String,sq_String]:=StringReplace[s,x:(sq..):>sq] s={ "", "\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln", "..1111111111111111111111111111111111111111111111111111111111111117777888", "I never give 'em hell, I just tell the truth, and they think it's hell. ", " --- Harry S Truman " }; Squeeze[s[[1]],""] Squeeze[s[[2]],"-"] Squeeze[s[[3]],"7"] Squeeze[s[[4]],"."] Squeeze[s[[5]]," "] Squeeze[s[[5]],"-"] Squeeze[s[[5]],"r"]
using System; using static System.Linq.Enumerable; public class Program { static void Main() { SqueezeAndPrint("", ' '); SqueezeAndPrint("\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln ", '-'); SqueezeAndPrint("..1111111111111111111111111111111111111111111111111111111111111117777888", '7'); SqueezeAndPrint("I never give 'em hell, I just tell the truth, and they think it's hell. ", '.'); string s = " --- Harry S Truman "; SqueezeAndPrint(s, ' '); SqueezeAndPrint(s, '-'); SqueezeAndPrint(s, 'r'); } static void SqueezeAndPrint(string s, char c) { Console.WriteLine($"squeeze: '{c}'"); Console.WriteLine($"old: {s.Length} «««{s}»»»"); s = Squeeze(s, c); Console.WriteLine($"new: {s.Length} «««{s}»»»"); } static string Squeeze(string s, char c) => string.IsNullOrEmpty(s) ? "" : s[0] + new string(Range(1, s.Length - 1).Where(i => s[i] != c || s[i] != s[i - 1]).Select(i => s[i]).ToArray()); }
Convert this Mathematica block to C#, preserving its control flow and logic.
ClearAll[Squeeze] Squeeze[s_String,sq_String]:=StringReplace[s,x:(sq..):>sq] s={ "", "\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln", "..1111111111111111111111111111111111111111111111111111111111111117777888", "I never give 'em hell, I just tell the truth, and they think it's hell. ", " --- Harry S Truman " }; Squeeze[s[[1]],""] Squeeze[s[[2]],"-"] Squeeze[s[[3]],"7"] Squeeze[s[[4]],"."] Squeeze[s[[5]]," "] Squeeze[s[[5]],"-"] Squeeze[s[[5]],"r"]
using System; using static System.Linq.Enumerable; public class Program { static void Main() { SqueezeAndPrint("", ' '); SqueezeAndPrint("\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln ", '-'); SqueezeAndPrint("..1111111111111111111111111111111111111111111111111111111111111117777888", '7'); SqueezeAndPrint("I never give 'em hell, I just tell the truth, and they think it's hell. ", '.'); string s = " --- Harry S Truman "; SqueezeAndPrint(s, ' '); SqueezeAndPrint(s, '-'); SqueezeAndPrint(s, 'r'); } static void SqueezeAndPrint(string s, char c) { Console.WriteLine($"squeeze: '{c}'"); Console.WriteLine($"old: {s.Length} «««{s}»»»"); s = Squeeze(s, c); Console.WriteLine($"new: {s.Length} «««{s}»»»"); } static string Squeeze(string s, char c) => string.IsNullOrEmpty(s) ? "" : s[0] + new string(Range(1, s.Length - 1).Where(i => s[i] != c || s[i] != s[i - 1]).Select(i => s[i]).ToArray()); }
Change the programming language of this snippet from Mathematica to C++ without modifying what it does.
ClearAll[Squeeze] Squeeze[s_String,sq_String]:=StringReplace[s,x:(sq..):>sq] s={ "", "\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln", "..1111111111111111111111111111111111111111111111111111111111111117777888", "I never give 'em hell, I just tell the truth, and they think it's hell. ", " --- Harry S Truman " }; Squeeze[s[[1]],""] Squeeze[s[[2]],"-"] Squeeze[s[[3]],"7"] Squeeze[s[[4]],"."] Squeeze[s[[5]]," "] Squeeze[s[[5]],"-"] Squeeze[s[[5]],"r"]
#include <algorithm> #include <string> #include <iostream> template<typename char_type> std::basic_string<char_type> squeeze(std::basic_string<char_type> str, char_type ch) { auto i = std::unique(str.begin(), str.end(), [ch](char_type a, char_type b) { return a == ch && b == ch; }); str.erase(i, str.end()); return str; } void test(const std::string& str, char ch) { std::cout << "character: '" << ch << "'\n"; std::cout << "original: <<<" << str << ">>>, length: " << str.length() << '\n'; std::string squeezed(squeeze(str, ch)); std::cout << "result: <<<" << squeezed << ">>>, length: " << squeezed.length() << '\n'; std::cout << '\n'; } int main(int argc, char** argv) { test("", ' '); test("\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln ", '-'); test("..1111111111111111111111111111111111111111111111111111111111111117777888", '7'); test("I never give 'em hell, I just tell the truth, and they think it's hell. ", '.'); std::string truman(" --- Harry S Truman "); test(truman, ' '); test(truman, '-'); test(truman, 'r'); return 0; }
Rewrite the snippet below in C++ so it works the same as the original Mathematica code.
ClearAll[Squeeze] Squeeze[s_String,sq_String]:=StringReplace[s,x:(sq..):>sq] s={ "", "\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln", "..1111111111111111111111111111111111111111111111111111111111111117777888", "I never give 'em hell, I just tell the truth, and they think it's hell. ", " --- Harry S Truman " }; Squeeze[s[[1]],""] Squeeze[s[[2]],"-"] Squeeze[s[[3]],"7"] Squeeze[s[[4]],"."] Squeeze[s[[5]]," "] Squeeze[s[[5]],"-"] Squeeze[s[[5]],"r"]
#include <algorithm> #include <string> #include <iostream> template<typename char_type> std::basic_string<char_type> squeeze(std::basic_string<char_type> str, char_type ch) { auto i = std::unique(str.begin(), str.end(), [ch](char_type a, char_type b) { return a == ch && b == ch; }); str.erase(i, str.end()); return str; } void test(const std::string& str, char ch) { std::cout << "character: '" << ch << "'\n"; std::cout << "original: <<<" << str << ">>>, length: " << str.length() << '\n'; std::string squeezed(squeeze(str, ch)); std::cout << "result: <<<" << squeezed << ">>>, length: " << squeezed.length() << '\n'; std::cout << '\n'; } int main(int argc, char** argv) { test("", ' '); test("\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln ", '-'); test("..1111111111111111111111111111111111111111111111111111111111111117777888", '7'); test("I never give 'em hell, I just tell the truth, and they think it's hell. ", '.'); std::string truman(" --- Harry S Truman "); test(truman, ' '); test(truman, '-'); test(truman, 'r'); return 0; }
Transform the following Mathematica implementation into Java, maintaining the same output and logic.
ClearAll[Squeeze] Squeeze[s_String,sq_String]:=StringReplace[s,x:(sq..):>sq] s={ "", "\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln", "..1111111111111111111111111111111111111111111111111111111111111117777888", "I never give 'em hell, I just tell the truth, and they think it's hell. ", " --- Harry S Truman " }; Squeeze[s[[1]],""] Squeeze[s[[2]],"-"] Squeeze[s[[3]],"7"] Squeeze[s[[4]],"."] Squeeze[s[[5]]," "] Squeeze[s[[5]],"-"] Squeeze[s[[5]],"r"]
public class StringSqueezable { public static void main(String[] args) { String[] testStrings = new String[] { "", "\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln ", "..1111111111111111111111111111111111111111111111111111111111111117777888", "I never give 'em hell, I just tell the truth, and they think it's hell. ", " --- Harry S Truman ", "122333444455555666666777777788888888999999999", "The better the 4-wheel drive, the further you'll be from help when ya get stuck!", "headmistressship"}; String[] testChar = new String[] { " ", "-", "7", ".", " -r", "5", "e", "s"}; for ( int testNum = 0 ; testNum < testStrings.length ; testNum++ ) { String s = testStrings[testNum]; for ( char c : testChar[testNum].toCharArray() ) { String result = squeeze(s, c); System.out.printf("use: '%c'%nold: %2d <<<%s>>>%nnew: %2d <<<%s>>>%n%n", c, s.length(), s, result.length(), result); } } } private static String squeeze(String in, char include) { StringBuilder sb = new StringBuilder(); for ( int i = 0 ; i < in.length() ; i++ ) { if ( i == 0 || in.charAt(i-1) != in.charAt(i) || (in.charAt(i-1) == in.charAt(i) && in.charAt(i) != include)) { sb.append(in.charAt(i)); } } return sb.toString(); } }
Rewrite the snippet below in Java so it works the same as the original Mathematica code.
ClearAll[Squeeze] Squeeze[s_String,sq_String]:=StringReplace[s,x:(sq..):>sq] s={ "", "\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln", "..1111111111111111111111111111111111111111111111111111111111111117777888", "I never give 'em hell, I just tell the truth, and they think it's hell. ", " --- Harry S Truman " }; Squeeze[s[[1]],""] Squeeze[s[[2]],"-"] Squeeze[s[[3]],"7"] Squeeze[s[[4]],"."] Squeeze[s[[5]]," "] Squeeze[s[[5]],"-"] Squeeze[s[[5]],"r"]
public class StringSqueezable { public static void main(String[] args) { String[] testStrings = new String[] { "", "\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln ", "..1111111111111111111111111111111111111111111111111111111111111117777888", "I never give 'em hell, I just tell the truth, and they think it's hell. ", " --- Harry S Truman ", "122333444455555666666777777788888888999999999", "The better the 4-wheel drive, the further you'll be from help when ya get stuck!", "headmistressship"}; String[] testChar = new String[] { " ", "-", "7", ".", " -r", "5", "e", "s"}; for ( int testNum = 0 ; testNum < testStrings.length ; testNum++ ) { String s = testStrings[testNum]; for ( char c : testChar[testNum].toCharArray() ) { String result = squeeze(s, c); System.out.printf("use: '%c'%nold: %2d <<<%s>>>%nnew: %2d <<<%s>>>%n%n", c, s.length(), s, result.length(), result); } } } private static String squeeze(String in, char include) { StringBuilder sb = new StringBuilder(); for ( int i = 0 ; i < in.length() ; i++ ) { if ( i == 0 || in.charAt(i-1) != in.charAt(i) || (in.charAt(i-1) == in.charAt(i) && in.charAt(i) != include)) { sb.append(in.charAt(i)); } } return sb.toString(); } }
Change the following Mathematica code into Python without altering its purpose.
ClearAll[Squeeze] Squeeze[s_String,sq_String]:=StringReplace[s,x:(sq..):>sq] s={ "", "\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln", "..1111111111111111111111111111111111111111111111111111111111111117777888", "I never give 'em hell, I just tell the truth, and they think it's hell. ", " --- Harry S Truman " }; Squeeze[s[[1]],""] Squeeze[s[[2]],"-"] Squeeze[s[[3]],"7"] Squeeze[s[[4]],"."] Squeeze[s[[5]]," "] Squeeze[s[[5]],"-"] Squeeze[s[[5]],"r"]
from itertools import groupby def squeezer(s, txt): return ''.join(item if item == s else ''.join(grp) for item, grp in groupby(txt)) if __name__ == '__main__': strings = [ "", '"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln ', "..1111111111111111111111111111111111111111111111111111111111111117777888", "I never give 'em hell, I just tell the truth, and they think it's hell. ", " --- Harry S Truman ", "The better the 4-wheel drive, the further you'll be from help when ya get stuck!", "headmistressship", "aardvark", "πŸ˜πŸ˜€πŸ™ŒπŸ’ƒπŸ˜πŸ˜πŸ˜πŸ™Œ", ] squeezers = ' ,-,7,., -r,e,s,a,😍'.split(',') for txt, chars in zip(strings, squeezers): this = "Original" print(f"\n{this:14} Size: {len(txt)} «««{txt}»»»" ) for ch in chars: this = f"Squeezer '{ch}'" sqz = squeezer(ch, txt) print(f"{this:>14} Size: {len(sqz)} «««{sqz}»»»" )
Convert this Mathematica block to Python, preserving its control flow and logic.
ClearAll[Squeeze] Squeeze[s_String,sq_String]:=StringReplace[s,x:(sq..):>sq] s={ "", "\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln", "..1111111111111111111111111111111111111111111111111111111111111117777888", "I never give 'em hell, I just tell the truth, and they think it's hell. ", " --- Harry S Truman " }; Squeeze[s[[1]],""] Squeeze[s[[2]],"-"] Squeeze[s[[3]],"7"] Squeeze[s[[4]],"."] Squeeze[s[[5]]," "] Squeeze[s[[5]],"-"] Squeeze[s[[5]],"r"]
from itertools import groupby def squeezer(s, txt): return ''.join(item if item == s else ''.join(grp) for item, grp in groupby(txt)) if __name__ == '__main__': strings = [ "", '"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln ', "..1111111111111111111111111111111111111111111111111111111111111117777888", "I never give 'em hell, I just tell the truth, and they think it's hell. ", " --- Harry S Truman ", "The better the 4-wheel drive, the further you'll be from help when ya get stuck!", "headmistressship", "aardvark", "πŸ˜πŸ˜€πŸ™ŒπŸ’ƒπŸ˜πŸ˜πŸ˜πŸ™Œ", ] squeezers = ' ,-,7,., -r,e,s,a,😍'.split(',') for txt, chars in zip(strings, squeezers): this = "Original" print(f"\n{this:14} Size: {len(txt)} «««{txt}»»»" ) for ch in chars: this = f"Squeezer '{ch}'" sqz = squeezer(ch, txt) print(f"{this:>14} Size: {len(sqz)} «««{sqz}»»»" )
Produce a language-to-language conversion: from Mathematica to VB, same semantics.
ClearAll[Squeeze] Squeeze[s_String,sq_String]:=StringReplace[s,x:(sq..):>sq] s={ "", "\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln", "..1111111111111111111111111111111111111111111111111111111111111117777888", "I never give 'em hell, I just tell the truth, and they think it's hell. ", " --- Harry S Truman " }; Squeeze[s[[1]],""] Squeeze[s[[2]],"-"] Squeeze[s[[3]],"7"] Squeeze[s[[4]],"."] Squeeze[s[[5]]," "] Squeeze[s[[5]],"-"] Squeeze[s[[5]],"r"]
Imports System.Linq.Enumerable Module Module1 Function Squeeze(s As String, c As Char) As String If String.IsNullOrEmpty(s) Then Return "" End If Return s(0) + New String(Range(1, s.Length - 1).Where(Function(i) s(i) <> c OrElse s(i) <> s(i - 1)).Select(Function(i) s(i)).ToArray()) End Function Sub SqueezeAndPrint(s As String, c As Char) Console.WriteLine("squeeze: Console.WriteLine("old: {0} «««{1}»»»", s.Length, s) s = Squeeze(s, c) Console.WriteLine("new: {0} «««{1}»»»", s.Length, s) End Sub Sub Main() Const QUOTE = """" SqueezeAndPrint("", " ") SqueezeAndPrint(QUOTE & "If I were two-faced, would I be wearing this one?" & QUOTE & " --- Abraham Lincoln ", "-") SqueezeAndPrint("..1111111111111111111111111111111111111111111111111111111111111117777888", "7") SqueezeAndPrint("I never give Dim s = " --- Harry S Truman " SqueezeAndPrint(s, " ") SqueezeAndPrint(s, "-") SqueezeAndPrint(s, "r") End Sub End Module
Can you help me rewrite this code in VB instead of Mathematica, keeping it the same logically?
ClearAll[Squeeze] Squeeze[s_String,sq_String]:=StringReplace[s,x:(sq..):>sq] s={ "", "\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln", "..1111111111111111111111111111111111111111111111111111111111111117777888", "I never give 'em hell, I just tell the truth, and they think it's hell. ", " --- Harry S Truman " }; Squeeze[s[[1]],""] Squeeze[s[[2]],"-"] Squeeze[s[[3]],"7"] Squeeze[s[[4]],"."] Squeeze[s[[5]]," "] Squeeze[s[[5]],"-"] Squeeze[s[[5]],"r"]
Imports System.Linq.Enumerable Module Module1 Function Squeeze(s As String, c As Char) As String If String.IsNullOrEmpty(s) Then Return "" End If Return s(0) + New String(Range(1, s.Length - 1).Where(Function(i) s(i) <> c OrElse s(i) <> s(i - 1)).Select(Function(i) s(i)).ToArray()) End Function Sub SqueezeAndPrint(s As String, c As Char) Console.WriteLine("squeeze: Console.WriteLine("old: {0} «««{1}»»»", s.Length, s) s = Squeeze(s, c) Console.WriteLine("new: {0} «««{1}»»»", s.Length, s) End Sub Sub Main() Const QUOTE = """" SqueezeAndPrint("", " ") SqueezeAndPrint(QUOTE & "If I were two-faced, would I be wearing this one?" & QUOTE & " --- Abraham Lincoln ", "-") SqueezeAndPrint("..1111111111111111111111111111111111111111111111111111111111111117777888", "7") SqueezeAndPrint("I never give Dim s = " --- Harry S Truman " SqueezeAndPrint(s, " ") SqueezeAndPrint(s, "-") SqueezeAndPrint(s, "r") End Sub End Module
Translate the given Mathematica code snippet into Go without altering its behavior.
ClearAll[Squeeze] Squeeze[s_String,sq_String]:=StringReplace[s,x:(sq..):>sq] s={ "", "\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln", "..1111111111111111111111111111111111111111111111111111111111111117777888", "I never give 'em hell, I just tell the truth, and they think it's hell. ", " --- Harry S Truman " }; Squeeze[s[[1]],""] Squeeze[s[[2]],"-"] Squeeze[s[[3]],"7"] Squeeze[s[[4]],"."] Squeeze[s[[5]]," "] Squeeze[s[[5]],"-"] Squeeze[s[[5]],"r"]
package main import "fmt" func squeeze(s string, c rune) (string, int, int) { r := []rune(s) le, del := len(r), 0 for i := le - 2; i >= 0; i-- { if r[i] == c && r[i] == r[i+1] { copy(r[i:], r[i+1:]) del++ } } if del == 0 { return s, le, le } r = r[:le-del] return string(r), le, len(r) } func main() { strings := []string{ "", `"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln `, "..1111111111111111111111111111111111111111111111111111111111111117777888", "I never give 'em hell, I just tell the truth, and they think it's hell. ", " --- Harry S Truman ", "The better the 4-wheel drive, the further you'll be from help when ya get stuck!", "headmistressship", "aardvark", "πŸ˜πŸ˜€πŸ™ŒπŸ’ƒπŸ˜πŸ˜πŸ˜πŸ™Œ", } chars := [][]rune{{' '}, {'-'}, {'7'}, {'.'}, {' ', '-', 'r'}, {'e'}, {'s'}, {'a'}, {'😍'}} for i, s := range strings { for _, c := range chars[i] { ss, olen, slen := squeeze(s, c) fmt.Printf("specified character = %q\n", c) fmt.Printf("originalΒ : length = %2d, string = «««%s»»»\n", olen, s) fmt.Printf("squeezedΒ : length = %2d, string = «««%s»»»\n\n", slen, ss) } } }
Keep all operations the same but rewrite the snippet in Go.
ClearAll[Squeeze] Squeeze[s_String,sq_String]:=StringReplace[s,x:(sq..):>sq] s={ "", "\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln", "..1111111111111111111111111111111111111111111111111111111111111117777888", "I never give 'em hell, I just tell the truth, and they think it's hell. ", " --- Harry S Truman " }; Squeeze[s[[1]],""] Squeeze[s[[2]],"-"] Squeeze[s[[3]],"7"] Squeeze[s[[4]],"."] Squeeze[s[[5]]," "] Squeeze[s[[5]],"-"] Squeeze[s[[5]],"r"]
package main import "fmt" func squeeze(s string, c rune) (string, int, int) { r := []rune(s) le, del := len(r), 0 for i := le - 2; i >= 0; i-- { if r[i] == c && r[i] == r[i+1] { copy(r[i:], r[i+1:]) del++ } } if del == 0 { return s, le, le } r = r[:le-del] return string(r), le, len(r) } func main() { strings := []string{ "", `"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln `, "..1111111111111111111111111111111111111111111111111111111111111117777888", "I never give 'em hell, I just tell the truth, and they think it's hell. ", " --- Harry S Truman ", "The better the 4-wheel drive, the further you'll be from help when ya get stuck!", "headmistressship", "aardvark", "πŸ˜πŸ˜€πŸ™ŒπŸ’ƒπŸ˜πŸ˜πŸ˜πŸ™Œ", } chars := [][]rune{{' '}, {'-'}, {'7'}, {'.'}, {' ', '-', 'r'}, {'e'}, {'s'}, {'a'}, {'😍'}} for i, s := range strings { for _, c := range chars[i] { ss, olen, slen := squeeze(s, c) fmt.Printf("specified character = %q\n", c) fmt.Printf("originalΒ : length = %2d, string = «««%s»»»\n", olen, s) fmt.Printf("squeezedΒ : length = %2d, string = «««%s»»»\n\n", slen, ss) } } }
Translate the given MATLAB code snippet into C without altering its behavior.
function r = squeezee(s,c) ix = []; c = unique(c); for k=1:length(c) ix=[ix; find((s(1:end-1)==s(2:end)) & (s(1:end-1)==c(k)))+1]; end r=s; r(ix)=[]; fprintf(1,'Character to be squeezed: " fprintf(1,'Input: <<< fprintf(1,'Output: <<< fprintf(1,'Character to be squeezed: " end squeezee('', ' ') squeezee('β•‘β•šβ•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•—', '-') squeezee('β•‘"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln β•‘', '7') squeezee('β•‘..1111111111111111111111111111111111111111111111111111111111111117777888β•‘', '.') squeezee('β•‘I never give ''em hell, I just tell the truth, and they think it''s hell. β•‘', '.') squeezee('β•‘ --- Harry S Truman β•‘', '.') squeezee('β•‘ --- Harry S Truman β•‘', '-') squeezee('β•‘ --- Harry S Truman β•‘', 'r')
#include<string.h> #include<stdlib.h> #include<stdio.h> #define COLLAPSE 0 #define SQUEEZE 1 typedef struct charList{ char c; struct charList *next; } charList; int strcmpi(char str1[100],char str2[100]){ int len1 = strlen(str1), len2 = strlen(str2), i; if(len1!=len2){ return 1; } else{ for(i=0;i<len1;i++){ if((str1[i]>='A'&&str1[i]<='Z')&&(str2[i]>='a'&&str2[i]<='z')&&(str2[i]-65!=str1[i])) return 1; else if((str2[i]>='A'&&str2[i]<='Z')&&(str1[i]>='a'&&str1[i]<='z')&&(str1[i]-65!=str2[i])) return 1; else if(str1[i]!=str2[i]) return 1; } } return 0; } charList *strToCharList(char* str){ int len = strlen(str),i; charList *list, *iterator, *nextChar; list = (charList*)malloc(sizeof(charList)); list->c = str[0]; list->next = NULL; iterator = list; for(i=1;i<len;i++){ nextChar = (charList*)malloc(sizeof(charList)); nextChar->c = str[i]; nextChar->next = NULL; iterator->next = nextChar; iterator = nextChar; } return list; } char* charListToString(charList* list){ charList* iterator = list; int count = 0,i; char* str; while(iterator!=NULL){ count++; iterator = iterator->next; } str = (char*)malloc((count+1)*sizeof(char)); iterator = list; for(i=0;i<count;i++){ str[i] = iterator->c; iterator = iterator->next; } free(list); str[i] = '\0'; return str; } char* processString(char str[100],int operation, char squeezeChar){ charList *strList = strToCharList(str),*iterator = strList, *scout; if(operation==SQUEEZE){ while(iterator!=NULL){ if(iterator->c==squeezeChar){ scout = iterator->next; while(scout!=NULL && scout->c==squeezeChar){ iterator->next = scout->next; scout->next = NULL; free(scout); scout = iterator->next; } } iterator = iterator->next; } } else{ while(iterator!=NULL && iterator->next!=NULL){ if(iterator->c == (iterator->next)->c){ scout = iterator->next; squeezeChar = iterator->c; while(scout!=NULL && scout->c==squeezeChar){ iterator->next = scout->next; scout->next = NULL; free(scout); scout = iterator->next; } } iterator = iterator->next; } } return charListToString(strList); } void printResults(char originalString[100], char finalString[100], int operation, char squeezeChar){ if(operation==SQUEEZE){ printf("Specified OperationΒ : SQUEEZE\nTarget CharacterΒ : %c",squeezeChar); } else printf("Specified OperationΒ : COLLAPSE"); printf("\nOriginal %c%c%c%s%c%c%c\nLengthΒ : %d",174,174,174,originalString,175,175,175,(int)strlen(originalString)); printf("\nFinal %c%c%c%s%c%c%c\nLengthΒ : %d\n",174,174,174,finalString,175,175,175,(int)strlen(finalString)); } int main(int argc, char** argv){ int operation; char squeezeChar; if(argc<3||argc>4){ printf("UsageΒ : %s <SQUEEZE|COLLAPSE> <String to be processed> <Character to be squeezed, if operation is SQUEEZE>\n",argv[0]); return 0; } if(strcmpi(argv[1],"SQUEEZE")==0 && argc!=4){ scanf("Please enter characted to be squeezedΒ : %c",&squeezeChar); operation = SQUEEZE; } else if(argc==4){ operation = SQUEEZE; squeezeChar = argv[3][0]; } else if(strcmpi(argv[1],"COLLAPSE")==0){ operation = COLLAPSE; } if(strlen(argv[2])<2){ printResults(argv[2],argv[2],operation,squeezeChar); } else{ printResults(argv[2],processString(argv[2],operation,squeezeChar),operation,squeezeChar); } return 0; }
Rewrite this program in C while keeping its functionality equivalent to the MATLAB version.
function r = squeezee(s,c) ix = []; c = unique(c); for k=1:length(c) ix=[ix; find((s(1:end-1)==s(2:end)) & (s(1:end-1)==c(k)))+1]; end r=s; r(ix)=[]; fprintf(1,'Character to be squeezed: " fprintf(1,'Input: <<< fprintf(1,'Output: <<< fprintf(1,'Character to be squeezed: " end squeezee('', ' ') squeezee('β•‘β•šβ•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•—', '-') squeezee('β•‘"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln β•‘', '7') squeezee('β•‘..1111111111111111111111111111111111111111111111111111111111111117777888β•‘', '.') squeezee('β•‘I never give ''em hell, I just tell the truth, and they think it''s hell. β•‘', '.') squeezee('β•‘ --- Harry S Truman β•‘', '.') squeezee('β•‘ --- Harry S Truman β•‘', '-') squeezee('β•‘ --- Harry S Truman β•‘', 'r')
#include<string.h> #include<stdlib.h> #include<stdio.h> #define COLLAPSE 0 #define SQUEEZE 1 typedef struct charList{ char c; struct charList *next; } charList; int strcmpi(char str1[100],char str2[100]){ int len1 = strlen(str1), len2 = strlen(str2), i; if(len1!=len2){ return 1; } else{ for(i=0;i<len1;i++){ if((str1[i]>='A'&&str1[i]<='Z')&&(str2[i]>='a'&&str2[i]<='z')&&(str2[i]-65!=str1[i])) return 1; else if((str2[i]>='A'&&str2[i]<='Z')&&(str1[i]>='a'&&str1[i]<='z')&&(str1[i]-65!=str2[i])) return 1; else if(str1[i]!=str2[i]) return 1; } } return 0; } charList *strToCharList(char* str){ int len = strlen(str),i; charList *list, *iterator, *nextChar; list = (charList*)malloc(sizeof(charList)); list->c = str[0]; list->next = NULL; iterator = list; for(i=1;i<len;i++){ nextChar = (charList*)malloc(sizeof(charList)); nextChar->c = str[i]; nextChar->next = NULL; iterator->next = nextChar; iterator = nextChar; } return list; } char* charListToString(charList* list){ charList* iterator = list; int count = 0,i; char* str; while(iterator!=NULL){ count++; iterator = iterator->next; } str = (char*)malloc((count+1)*sizeof(char)); iterator = list; for(i=0;i<count;i++){ str[i] = iterator->c; iterator = iterator->next; } free(list); str[i] = '\0'; return str; } char* processString(char str[100],int operation, char squeezeChar){ charList *strList = strToCharList(str),*iterator = strList, *scout; if(operation==SQUEEZE){ while(iterator!=NULL){ if(iterator->c==squeezeChar){ scout = iterator->next; while(scout!=NULL && scout->c==squeezeChar){ iterator->next = scout->next; scout->next = NULL; free(scout); scout = iterator->next; } } iterator = iterator->next; } } else{ while(iterator!=NULL && iterator->next!=NULL){ if(iterator->c == (iterator->next)->c){ scout = iterator->next; squeezeChar = iterator->c; while(scout!=NULL && scout->c==squeezeChar){ iterator->next = scout->next; scout->next = NULL; free(scout); scout = iterator->next; } } iterator = iterator->next; } } return charListToString(strList); } void printResults(char originalString[100], char finalString[100], int operation, char squeezeChar){ if(operation==SQUEEZE){ printf("Specified OperationΒ : SQUEEZE\nTarget CharacterΒ : %c",squeezeChar); } else printf("Specified OperationΒ : COLLAPSE"); printf("\nOriginal %c%c%c%s%c%c%c\nLengthΒ : %d",174,174,174,originalString,175,175,175,(int)strlen(originalString)); printf("\nFinal %c%c%c%s%c%c%c\nLengthΒ : %d\n",174,174,174,finalString,175,175,175,(int)strlen(finalString)); } int main(int argc, char** argv){ int operation; char squeezeChar; if(argc<3||argc>4){ printf("UsageΒ : %s <SQUEEZE|COLLAPSE> <String to be processed> <Character to be squeezed, if operation is SQUEEZE>\n",argv[0]); return 0; } if(strcmpi(argv[1],"SQUEEZE")==0 && argc!=4){ scanf("Please enter characted to be squeezedΒ : %c",&squeezeChar); operation = SQUEEZE; } else if(argc==4){ operation = SQUEEZE; squeezeChar = argv[3][0]; } else if(strcmpi(argv[1],"COLLAPSE")==0){ operation = COLLAPSE; } if(strlen(argv[2])<2){ printResults(argv[2],argv[2],operation,squeezeChar); } else{ printResults(argv[2],processString(argv[2],operation,squeezeChar),operation,squeezeChar); } return 0; }
Please provide an equivalent version of this MATLAB code in C#.
function r = squeezee(s,c) ix = []; c = unique(c); for k=1:length(c) ix=[ix; find((s(1:end-1)==s(2:end)) & (s(1:end-1)==c(k)))+1]; end r=s; r(ix)=[]; fprintf(1,'Character to be squeezed: " fprintf(1,'Input: <<< fprintf(1,'Output: <<< fprintf(1,'Character to be squeezed: " end squeezee('', ' ') squeezee('β•‘β•šβ•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•—', '-') squeezee('β•‘"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln β•‘', '7') squeezee('β•‘..1111111111111111111111111111111111111111111111111111111111111117777888β•‘', '.') squeezee('β•‘I never give ''em hell, I just tell the truth, and they think it''s hell. β•‘', '.') squeezee('β•‘ --- Harry S Truman β•‘', '.') squeezee('β•‘ --- Harry S Truman β•‘', '-') squeezee('β•‘ --- Harry S Truman β•‘', 'r')
using System; using static System.Linq.Enumerable; public class Program { static void Main() { SqueezeAndPrint("", ' '); SqueezeAndPrint("\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln ", '-'); SqueezeAndPrint("..1111111111111111111111111111111111111111111111111111111111111117777888", '7'); SqueezeAndPrint("I never give 'em hell, I just tell the truth, and they think it's hell. ", '.'); string s = " --- Harry S Truman "; SqueezeAndPrint(s, ' '); SqueezeAndPrint(s, '-'); SqueezeAndPrint(s, 'r'); } static void SqueezeAndPrint(string s, char c) { Console.WriteLine($"squeeze: '{c}'"); Console.WriteLine($"old: {s.Length} «««{s}»»»"); s = Squeeze(s, c); Console.WriteLine($"new: {s.Length} «««{s}»»»"); } static string Squeeze(string s, char c) => string.IsNullOrEmpty(s) ? "" : s[0] + new string(Range(1, s.Length - 1).Where(i => s[i] != c || s[i] != s[i - 1]).Select(i => s[i]).ToArray()); }
Produce a functionally identical C# code for the snippet given in MATLAB.
function r = squeezee(s,c) ix = []; c = unique(c); for k=1:length(c) ix=[ix; find((s(1:end-1)==s(2:end)) & (s(1:end-1)==c(k)))+1]; end r=s; r(ix)=[]; fprintf(1,'Character to be squeezed: " fprintf(1,'Input: <<< fprintf(1,'Output: <<< fprintf(1,'Character to be squeezed: " end squeezee('', ' ') squeezee('β•‘β•šβ•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•—', '-') squeezee('β•‘"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln β•‘', '7') squeezee('β•‘..1111111111111111111111111111111111111111111111111111111111111117777888β•‘', '.') squeezee('β•‘I never give ''em hell, I just tell the truth, and they think it''s hell. β•‘', '.') squeezee('β•‘ --- Harry S Truman β•‘', '.') squeezee('β•‘ --- Harry S Truman β•‘', '-') squeezee('β•‘ --- Harry S Truman β•‘', 'r')
using System; using static System.Linq.Enumerable; public class Program { static void Main() { SqueezeAndPrint("", ' '); SqueezeAndPrint("\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln ", '-'); SqueezeAndPrint("..1111111111111111111111111111111111111111111111111111111111111117777888", '7'); SqueezeAndPrint("I never give 'em hell, I just tell the truth, and they think it's hell. ", '.'); string s = " --- Harry S Truman "; SqueezeAndPrint(s, ' '); SqueezeAndPrint(s, '-'); SqueezeAndPrint(s, 'r'); } static void SqueezeAndPrint(string s, char c) { Console.WriteLine($"squeeze: '{c}'"); Console.WriteLine($"old: {s.Length} «««{s}»»»"); s = Squeeze(s, c); Console.WriteLine($"new: {s.Length} «««{s}»»»"); } static string Squeeze(string s, char c) => string.IsNullOrEmpty(s) ? "" : s[0] + new string(Range(1, s.Length - 1).Where(i => s[i] != c || s[i] != s[i - 1]).Select(i => s[i]).ToArray()); }
Change the programming language of this snippet from MATLAB to C++ without modifying what it does.
function r = squeezee(s,c) ix = []; c = unique(c); for k=1:length(c) ix=[ix; find((s(1:end-1)==s(2:end)) & (s(1:end-1)==c(k)))+1]; end r=s; r(ix)=[]; fprintf(1,'Character to be squeezed: " fprintf(1,'Input: <<< fprintf(1,'Output: <<< fprintf(1,'Character to be squeezed: " end squeezee('', ' ') squeezee('β•‘β•šβ•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•—', '-') squeezee('β•‘"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln β•‘', '7') squeezee('β•‘..1111111111111111111111111111111111111111111111111111111111111117777888β•‘', '.') squeezee('β•‘I never give ''em hell, I just tell the truth, and they think it''s hell. β•‘', '.') squeezee('β•‘ --- Harry S Truman β•‘', '.') squeezee('β•‘ --- Harry S Truman β•‘', '-') squeezee('β•‘ --- Harry S Truman β•‘', 'r')
#include <algorithm> #include <string> #include <iostream> template<typename char_type> std::basic_string<char_type> squeeze(std::basic_string<char_type> str, char_type ch) { auto i = std::unique(str.begin(), str.end(), [ch](char_type a, char_type b) { return a == ch && b == ch; }); str.erase(i, str.end()); return str; } void test(const std::string& str, char ch) { std::cout << "character: '" << ch << "'\n"; std::cout << "original: <<<" << str << ">>>, length: " << str.length() << '\n'; std::string squeezed(squeeze(str, ch)); std::cout << "result: <<<" << squeezed << ">>>, length: " << squeezed.length() << '\n'; std::cout << '\n'; } int main(int argc, char** argv) { test("", ' '); test("\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln ", '-'); test("..1111111111111111111111111111111111111111111111111111111111111117777888", '7'); test("I never give 'em hell, I just tell the truth, and they think it's hell. ", '.'); std::string truman(" --- Harry S Truman "); test(truman, ' '); test(truman, '-'); test(truman, 'r'); return 0; }
Convert this MATLAB snippet to C++ and keep its semantics consistent.
function r = squeezee(s,c) ix = []; c = unique(c); for k=1:length(c) ix=[ix; find((s(1:end-1)==s(2:end)) & (s(1:end-1)==c(k)))+1]; end r=s; r(ix)=[]; fprintf(1,'Character to be squeezed: " fprintf(1,'Input: <<< fprintf(1,'Output: <<< fprintf(1,'Character to be squeezed: " end squeezee('', ' ') squeezee('β•‘β•šβ•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•—', '-') squeezee('β•‘"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln β•‘', '7') squeezee('β•‘..1111111111111111111111111111111111111111111111111111111111111117777888β•‘', '.') squeezee('β•‘I never give ''em hell, I just tell the truth, and they think it''s hell. β•‘', '.') squeezee('β•‘ --- Harry S Truman β•‘', '.') squeezee('β•‘ --- Harry S Truman β•‘', '-') squeezee('β•‘ --- Harry S Truman β•‘', 'r')
#include <algorithm> #include <string> #include <iostream> template<typename char_type> std::basic_string<char_type> squeeze(std::basic_string<char_type> str, char_type ch) { auto i = std::unique(str.begin(), str.end(), [ch](char_type a, char_type b) { return a == ch && b == ch; }); str.erase(i, str.end()); return str; } void test(const std::string& str, char ch) { std::cout << "character: '" << ch << "'\n"; std::cout << "original: <<<" << str << ">>>, length: " << str.length() << '\n'; std::string squeezed(squeeze(str, ch)); std::cout << "result: <<<" << squeezed << ">>>, length: " << squeezed.length() << '\n'; std::cout << '\n'; } int main(int argc, char** argv) { test("", ' '); test("\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln ", '-'); test("..1111111111111111111111111111111111111111111111111111111111111117777888", '7'); test("I never give 'em hell, I just tell the truth, and they think it's hell. ", '.'); std::string truman(" --- Harry S Truman "); test(truman, ' '); test(truman, '-'); test(truman, 'r'); return 0; }
Write the same algorithm in Java as shown in this MATLAB implementation.
function r = squeezee(s,c) ix = []; c = unique(c); for k=1:length(c) ix=[ix; find((s(1:end-1)==s(2:end)) & (s(1:end-1)==c(k)))+1]; end r=s; r(ix)=[]; fprintf(1,'Character to be squeezed: " fprintf(1,'Input: <<< fprintf(1,'Output: <<< fprintf(1,'Character to be squeezed: " end squeezee('', ' ') squeezee('β•‘β•šβ•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•—', '-') squeezee('β•‘"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln β•‘', '7') squeezee('β•‘..1111111111111111111111111111111111111111111111111111111111111117777888β•‘', '.') squeezee('β•‘I never give ''em hell, I just tell the truth, and they think it''s hell. β•‘', '.') squeezee('β•‘ --- Harry S Truman β•‘', '.') squeezee('β•‘ --- Harry S Truman β•‘', '-') squeezee('β•‘ --- Harry S Truman β•‘', 'r')
public class StringSqueezable { public static void main(String[] args) { String[] testStrings = new String[] { "", "\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln ", "..1111111111111111111111111111111111111111111111111111111111111117777888", "I never give 'em hell, I just tell the truth, and they think it's hell. ", " --- Harry S Truman ", "122333444455555666666777777788888888999999999", "The better the 4-wheel drive, the further you'll be from help when ya get stuck!", "headmistressship"}; String[] testChar = new String[] { " ", "-", "7", ".", " -r", "5", "e", "s"}; for ( int testNum = 0 ; testNum < testStrings.length ; testNum++ ) { String s = testStrings[testNum]; for ( char c : testChar[testNum].toCharArray() ) { String result = squeeze(s, c); System.out.printf("use: '%c'%nold: %2d <<<%s>>>%nnew: %2d <<<%s>>>%n%n", c, s.length(), s, result.length(), result); } } } private static String squeeze(String in, char include) { StringBuilder sb = new StringBuilder(); for ( int i = 0 ; i < in.length() ; i++ ) { if ( i == 0 || in.charAt(i-1) != in.charAt(i) || (in.charAt(i-1) == in.charAt(i) && in.charAt(i) != include)) { sb.append(in.charAt(i)); } } return sb.toString(); } }
Keep all operations the same but rewrite the snippet in Java.
function r = squeezee(s,c) ix = []; c = unique(c); for k=1:length(c) ix=[ix; find((s(1:end-1)==s(2:end)) & (s(1:end-1)==c(k)))+1]; end r=s; r(ix)=[]; fprintf(1,'Character to be squeezed: " fprintf(1,'Input: <<< fprintf(1,'Output: <<< fprintf(1,'Character to be squeezed: " end squeezee('', ' ') squeezee('β•‘β•šβ•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•—', '-') squeezee('β•‘"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln β•‘', '7') squeezee('β•‘..1111111111111111111111111111111111111111111111111111111111111117777888β•‘', '.') squeezee('β•‘I never give ''em hell, I just tell the truth, and they think it''s hell. β•‘', '.') squeezee('β•‘ --- Harry S Truman β•‘', '.') squeezee('β•‘ --- Harry S Truman β•‘', '-') squeezee('β•‘ --- Harry S Truman β•‘', 'r')
public class StringSqueezable { public static void main(String[] args) { String[] testStrings = new String[] { "", "\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln ", "..1111111111111111111111111111111111111111111111111111111111111117777888", "I never give 'em hell, I just tell the truth, and they think it's hell. ", " --- Harry S Truman ", "122333444455555666666777777788888888999999999", "The better the 4-wheel drive, the further you'll be from help when ya get stuck!", "headmistressship"}; String[] testChar = new String[] { " ", "-", "7", ".", " -r", "5", "e", "s"}; for ( int testNum = 0 ; testNum < testStrings.length ; testNum++ ) { String s = testStrings[testNum]; for ( char c : testChar[testNum].toCharArray() ) { String result = squeeze(s, c); System.out.printf("use: '%c'%nold: %2d <<<%s>>>%nnew: %2d <<<%s>>>%n%n", c, s.length(), s, result.length(), result); } } } private static String squeeze(String in, char include) { StringBuilder sb = new StringBuilder(); for ( int i = 0 ; i < in.length() ; i++ ) { if ( i == 0 || in.charAt(i-1) != in.charAt(i) || (in.charAt(i-1) == in.charAt(i) && in.charAt(i) != include)) { sb.append(in.charAt(i)); } } return sb.toString(); } }
Translate this program into Python but keep the logic exactly as in MATLAB.
function r = squeezee(s,c) ix = []; c = unique(c); for k=1:length(c) ix=[ix; find((s(1:end-1)==s(2:end)) & (s(1:end-1)==c(k)))+1]; end r=s; r(ix)=[]; fprintf(1,'Character to be squeezed: " fprintf(1,'Input: <<< fprintf(1,'Output: <<< fprintf(1,'Character to be squeezed: " end squeezee('', ' ') squeezee('β•‘β•šβ•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•—', '-') squeezee('β•‘"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln β•‘', '7') squeezee('β•‘..1111111111111111111111111111111111111111111111111111111111111117777888β•‘', '.') squeezee('β•‘I never give ''em hell, I just tell the truth, and they think it''s hell. β•‘', '.') squeezee('β•‘ --- Harry S Truman β•‘', '.') squeezee('β•‘ --- Harry S Truman β•‘', '-') squeezee('β•‘ --- Harry S Truman β•‘', 'r')
from itertools import groupby def squeezer(s, txt): return ''.join(item if item == s else ''.join(grp) for item, grp in groupby(txt)) if __name__ == '__main__': strings = [ "", '"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln ', "..1111111111111111111111111111111111111111111111111111111111111117777888", "I never give 'em hell, I just tell the truth, and they think it's hell. ", " --- Harry S Truman ", "The better the 4-wheel drive, the further you'll be from help when ya get stuck!", "headmistressship", "aardvark", "πŸ˜πŸ˜€πŸ™ŒπŸ’ƒπŸ˜πŸ˜πŸ˜πŸ™Œ", ] squeezers = ' ,-,7,., -r,e,s,a,😍'.split(',') for txt, chars in zip(strings, squeezers): this = "Original" print(f"\n{this:14} Size: {len(txt)} «««{txt}»»»" ) for ch in chars: this = f"Squeezer '{ch}'" sqz = squeezer(ch, txt) print(f"{this:>14} Size: {len(sqz)} «««{sqz}»»»" )
Keep all operations the same but rewrite the snippet in Python.
function r = squeezee(s,c) ix = []; c = unique(c); for k=1:length(c) ix=[ix; find((s(1:end-1)==s(2:end)) & (s(1:end-1)==c(k)))+1]; end r=s; r(ix)=[]; fprintf(1,'Character to be squeezed: " fprintf(1,'Input: <<< fprintf(1,'Output: <<< fprintf(1,'Character to be squeezed: " end squeezee('', ' ') squeezee('β•‘β•šβ•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•—', '-') squeezee('β•‘"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln β•‘', '7') squeezee('β•‘..1111111111111111111111111111111111111111111111111111111111111117777888β•‘', '.') squeezee('β•‘I never give ''em hell, I just tell the truth, and they think it''s hell. β•‘', '.') squeezee('β•‘ --- Harry S Truman β•‘', '.') squeezee('β•‘ --- Harry S Truman β•‘', '-') squeezee('β•‘ --- Harry S Truman β•‘', 'r')
from itertools import groupby def squeezer(s, txt): return ''.join(item if item == s else ''.join(grp) for item, grp in groupby(txt)) if __name__ == '__main__': strings = [ "", '"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln ', "..1111111111111111111111111111111111111111111111111111111111111117777888", "I never give 'em hell, I just tell the truth, and they think it's hell. ", " --- Harry S Truman ", "The better the 4-wheel drive, the further you'll be from help when ya get stuck!", "headmistressship", "aardvark", "πŸ˜πŸ˜€πŸ™ŒπŸ’ƒπŸ˜πŸ˜πŸ˜πŸ™Œ", ] squeezers = ' ,-,7,., -r,e,s,a,😍'.split(',') for txt, chars in zip(strings, squeezers): this = "Original" print(f"\n{this:14} Size: {len(txt)} «««{txt}»»»" ) for ch in chars: this = f"Squeezer '{ch}'" sqz = squeezer(ch, txt) print(f"{this:>14} Size: {len(sqz)} «««{sqz}»»»" )
Convert this MATLAB block to VB, preserving its control flow and logic.
function r = squeezee(s,c) ix = []; c = unique(c); for k=1:length(c) ix=[ix; find((s(1:end-1)==s(2:end)) & (s(1:end-1)==c(k)))+1]; end r=s; r(ix)=[]; fprintf(1,'Character to be squeezed: " fprintf(1,'Input: <<< fprintf(1,'Output: <<< fprintf(1,'Character to be squeezed: " end squeezee('', ' ') squeezee('β•‘β•šβ•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•—', '-') squeezee('β•‘"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln β•‘', '7') squeezee('β•‘..1111111111111111111111111111111111111111111111111111111111111117777888β•‘', '.') squeezee('β•‘I never give ''em hell, I just tell the truth, and they think it''s hell. β•‘', '.') squeezee('β•‘ --- Harry S Truman β•‘', '.') squeezee('β•‘ --- Harry S Truman β•‘', '-') squeezee('β•‘ --- Harry S Truman β•‘', 'r')
Imports System.Linq.Enumerable Module Module1 Function Squeeze(s As String, c As Char) As String If String.IsNullOrEmpty(s) Then Return "" End If Return s(0) + New String(Range(1, s.Length - 1).Where(Function(i) s(i) <> c OrElse s(i) <> s(i - 1)).Select(Function(i) s(i)).ToArray()) End Function Sub SqueezeAndPrint(s As String, c As Char) Console.WriteLine("squeeze: Console.WriteLine("old: {0} «««{1}»»»", s.Length, s) s = Squeeze(s, c) Console.WriteLine("new: {0} «««{1}»»»", s.Length, s) End Sub Sub Main() Const QUOTE = """" SqueezeAndPrint("", " ") SqueezeAndPrint(QUOTE & "If I were two-faced, would I be wearing this one?" & QUOTE & " --- Abraham Lincoln ", "-") SqueezeAndPrint("..1111111111111111111111111111111111111111111111111111111111111117777888", "7") SqueezeAndPrint("I never give Dim s = " --- Harry S Truman " SqueezeAndPrint(s, " ") SqueezeAndPrint(s, "-") SqueezeAndPrint(s, "r") End Sub End Module
Can you help me rewrite this code in VB instead of MATLAB, keeping it the same logically?
function r = squeezee(s,c) ix = []; c = unique(c); for k=1:length(c) ix=[ix; find((s(1:end-1)==s(2:end)) & (s(1:end-1)==c(k)))+1]; end r=s; r(ix)=[]; fprintf(1,'Character to be squeezed: " fprintf(1,'Input: <<< fprintf(1,'Output: <<< fprintf(1,'Character to be squeezed: " end squeezee('', ' ') squeezee('β•‘β•šβ•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•—', '-') squeezee('β•‘"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln β•‘', '7') squeezee('β•‘..1111111111111111111111111111111111111111111111111111111111111117777888β•‘', '.') squeezee('β•‘I never give ''em hell, I just tell the truth, and they think it''s hell. β•‘', '.') squeezee('β•‘ --- Harry S Truman β•‘', '.') squeezee('β•‘ --- Harry S Truman β•‘', '-') squeezee('β•‘ --- Harry S Truman β•‘', 'r')
Imports System.Linq.Enumerable Module Module1 Function Squeeze(s As String, c As Char) As String If String.IsNullOrEmpty(s) Then Return "" End If Return s(0) + New String(Range(1, s.Length - 1).Where(Function(i) s(i) <> c OrElse s(i) <> s(i - 1)).Select(Function(i) s(i)).ToArray()) End Function Sub SqueezeAndPrint(s As String, c As Char) Console.WriteLine("squeeze: Console.WriteLine("old: {0} «««{1}»»»", s.Length, s) s = Squeeze(s, c) Console.WriteLine("new: {0} «««{1}»»»", s.Length, s) End Sub Sub Main() Const QUOTE = """" SqueezeAndPrint("", " ") SqueezeAndPrint(QUOTE & "If I were two-faced, would I be wearing this one?" & QUOTE & " --- Abraham Lincoln ", "-") SqueezeAndPrint("..1111111111111111111111111111111111111111111111111111111111111117777888", "7") SqueezeAndPrint("I never give Dim s = " --- Harry S Truman " SqueezeAndPrint(s, " ") SqueezeAndPrint(s, "-") SqueezeAndPrint(s, "r") End Sub End Module
Rewrite this program in Go while keeping its functionality equivalent to the MATLAB version.
function r = squeezee(s,c) ix = []; c = unique(c); for k=1:length(c) ix=[ix; find((s(1:end-1)==s(2:end)) & (s(1:end-1)==c(k)))+1]; end r=s; r(ix)=[]; fprintf(1,'Character to be squeezed: " fprintf(1,'Input: <<< fprintf(1,'Output: <<< fprintf(1,'Character to be squeezed: " end squeezee('', ' ') squeezee('β•‘β•šβ•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•—', '-') squeezee('β•‘"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln β•‘', '7') squeezee('β•‘..1111111111111111111111111111111111111111111111111111111111111117777888β•‘', '.') squeezee('β•‘I never give ''em hell, I just tell the truth, and they think it''s hell. β•‘', '.') squeezee('β•‘ --- Harry S Truman β•‘', '.') squeezee('β•‘ --- Harry S Truman β•‘', '-') squeezee('β•‘ --- Harry S Truman β•‘', 'r')
package main import "fmt" func squeeze(s string, c rune) (string, int, int) { r := []rune(s) le, del := len(r), 0 for i := le - 2; i >= 0; i-- { if r[i] == c && r[i] == r[i+1] { copy(r[i:], r[i+1:]) del++ } } if del == 0 { return s, le, le } r = r[:le-del] return string(r), le, len(r) } func main() { strings := []string{ "", `"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln `, "..1111111111111111111111111111111111111111111111111111111111111117777888", "I never give 'em hell, I just tell the truth, and they think it's hell. ", " --- Harry S Truman ", "The better the 4-wheel drive, the further you'll be from help when ya get stuck!", "headmistressship", "aardvark", "πŸ˜πŸ˜€πŸ™ŒπŸ’ƒπŸ˜πŸ˜πŸ˜πŸ™Œ", } chars := [][]rune{{' '}, {'-'}, {'7'}, {'.'}, {' ', '-', 'r'}, {'e'}, {'s'}, {'a'}, {'😍'}} for i, s := range strings { for _, c := range chars[i] { ss, olen, slen := squeeze(s, c) fmt.Printf("specified character = %q\n", c) fmt.Printf("originalΒ : length = %2d, string = «««%s»»»\n", olen, s) fmt.Printf("squeezedΒ : length = %2d, string = «««%s»»»\n\n", slen, ss) } } }
Convert the following code from MATLAB to Go, ensuring the logic remains intact.
function r = squeezee(s,c) ix = []; c = unique(c); for k=1:length(c) ix=[ix; find((s(1:end-1)==s(2:end)) & (s(1:end-1)==c(k)))+1]; end r=s; r(ix)=[]; fprintf(1,'Character to be squeezed: " fprintf(1,'Input: <<< fprintf(1,'Output: <<< fprintf(1,'Character to be squeezed: " end squeezee('', ' ') squeezee('β•‘β•šβ•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•—', '-') squeezee('β•‘"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln β•‘', '7') squeezee('β•‘..1111111111111111111111111111111111111111111111111111111111111117777888β•‘', '.') squeezee('β•‘I never give ''em hell, I just tell the truth, and they think it''s hell. β•‘', '.') squeezee('β•‘ --- Harry S Truman β•‘', '.') squeezee('β•‘ --- Harry S Truman β•‘', '-') squeezee('β•‘ --- Harry S Truman β•‘', 'r')
package main import "fmt" func squeeze(s string, c rune) (string, int, int) { r := []rune(s) le, del := len(r), 0 for i := le - 2; i >= 0; i-- { if r[i] == c && r[i] == r[i+1] { copy(r[i:], r[i+1:]) del++ } } if del == 0 { return s, le, le } r = r[:le-del] return string(r), le, len(r) } func main() { strings := []string{ "", `"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln `, "..1111111111111111111111111111111111111111111111111111111111111117777888", "I never give 'em hell, I just tell the truth, and they think it's hell. ", " --- Harry S Truman ", "The better the 4-wheel drive, the further you'll be from help when ya get stuck!", "headmistressship", "aardvark", "πŸ˜πŸ˜€πŸ™ŒπŸ’ƒπŸ˜πŸ˜πŸ˜πŸ™Œ", } chars := [][]rune{{' '}, {'-'}, {'7'}, {'.'}, {' ', '-', 'r'}, {'e'}, {'s'}, {'a'}, {'😍'}} for i, s := range strings { for _, c := range chars[i] { ss, olen, slen := squeeze(s, c) fmt.Printf("specified character = %q\n", c) fmt.Printf("originalΒ : length = %2d, string = «««%s»»»\n", olen, s) fmt.Printf("squeezedΒ : length = %2d, string = «««%s»»»\n\n", slen, ss) } } }