Instruction stringlengths 45 106 | input_code stringlengths 1 13.7k | output_code stringlengths 1 13.7k |
|---|---|---|
Produce a functionally identical C code for the snippet given in Nim. | import unicode, strformat
proc squeeze(s: string; ch: Rune) =
echo fmt"Specified character: '{ch}'"
let original = s.toRunes
echo fmt"Original: length = {original.len}, string = «««{s}»»»"
var previous = Rune(0)
var squeezed: seq[Rune]
for rune in original:
if rune != previous:
squeezed.add(rune)
previous = rune
elif rune != ch:
squeezed.add(rune)
echo fmt"Squeezed: length = {squeezed.len}, string = «««{squeezed}»»»"
echo ""
const 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",
"😍😀🙌💃😍😍😍🙌",]
const Chars = [@[Rune(' ')], @[Rune('-')], @[Rune('7')], @[Rune('.')],
@[Rune(' '), Rune('-'), Rune('r')],
@[Rune('e')], @[Rune('s')], @[Rune('a')], "😍".toRunes]
for i, s in Strings:
for ch in Chars[i]:
s.squeeze(ch)
| #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 Nim code into C while preserving the original functionality. | import unicode, strformat
proc squeeze(s: string; ch: Rune) =
echo fmt"Specified character: '{ch}'"
let original = s.toRunes
echo fmt"Original: length = {original.len}, string = «««{s}»»»"
var previous = Rune(0)
var squeezed: seq[Rune]
for rune in original:
if rune != previous:
squeezed.add(rune)
previous = rune
elif rune != ch:
squeezed.add(rune)
echo fmt"Squeezed: length = {squeezed.len}, string = «««{squeezed}»»»"
echo ""
const 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",
"😍😀🙌💃😍😍😍🙌",]
const Chars = [@[Rune(' ')], @[Rune('-')], @[Rune('7')], @[Rune('.')],
@[Rune(' '), Rune('-'), Rune('r')],
@[Rune('e')], @[Rune('s')], @[Rune('a')], "😍".toRunes]
for i, s in Strings:
for ch in Chars[i]:
s.squeeze(ch)
| #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 language-to-language conversion: from Nim to C#, same semantics. | import unicode, strformat
proc squeeze(s: string; ch: Rune) =
echo fmt"Specified character: '{ch}'"
let original = s.toRunes
echo fmt"Original: length = {original.len}, string = «««{s}»»»"
var previous = Rune(0)
var squeezed: seq[Rune]
for rune in original:
if rune != previous:
squeezed.add(rune)
previous = rune
elif rune != ch:
squeezed.add(rune)
echo fmt"Squeezed: length = {squeezed.len}, string = «««{squeezed}»»»"
echo ""
const 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",
"😍😀🙌💃😍😍😍🙌",]
const Chars = [@[Rune(' ')], @[Rune('-')], @[Rune('7')], @[Rune('.')],
@[Rune(' '), Rune('-'), Rune('r')],
@[Rune('e')], @[Rune('s')], @[Rune('a')], "😍".toRunes]
for i, s in Strings:
for ch in Chars[i]:
s.squeeze(ch)
| 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());
}
|
Please provide an equivalent version of this Nim code in C#. | import unicode, strformat
proc squeeze(s: string; ch: Rune) =
echo fmt"Specified character: '{ch}'"
let original = s.toRunes
echo fmt"Original: length = {original.len}, string = «««{s}»»»"
var previous = Rune(0)
var squeezed: seq[Rune]
for rune in original:
if rune != previous:
squeezed.add(rune)
previous = rune
elif rune != ch:
squeezed.add(rune)
echo fmt"Squeezed: length = {squeezed.len}, string = «««{squeezed}»»»"
echo ""
const 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",
"😍😀🙌💃😍😍😍🙌",]
const Chars = [@[Rune(' ')], @[Rune('-')], @[Rune('7')], @[Rune('.')],
@[Rune(' '), Rune('-'), Rune('r')],
@[Rune('e')], @[Rune('s')], @[Rune('a')], "😍".toRunes]
for i, s in Strings:
for ch in Chars[i]:
s.squeeze(ch)
| 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());
}
|
Rewrite this program in C++ while keeping its functionality equivalent to the Nim version. | import unicode, strformat
proc squeeze(s: string; ch: Rune) =
echo fmt"Specified character: '{ch}'"
let original = s.toRunes
echo fmt"Original: length = {original.len}, string = «««{s}»»»"
var previous = Rune(0)
var squeezed: seq[Rune]
for rune in original:
if rune != previous:
squeezed.add(rune)
previous = rune
elif rune != ch:
squeezed.add(rune)
echo fmt"Squeezed: length = {squeezed.len}, string = «««{squeezed}»»»"
echo ""
const 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",
"😍😀🙌💃😍😍😍🙌",]
const Chars = [@[Rune(' ')], @[Rune('-')], @[Rune('7')], @[Rune('.')],
@[Rune(' '), Rune('-'), Rune('r')],
@[Rune('e')], @[Rune('s')], @[Rune('a')], "😍".toRunes]
for i, s in Strings:
for ch in Chars[i]:
s.squeeze(ch)
| #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;
}
|
Ensure the translated C++ code behaves exactly like the original Nim snippet. | import unicode, strformat
proc squeeze(s: string; ch: Rune) =
echo fmt"Specified character: '{ch}'"
let original = s.toRunes
echo fmt"Original: length = {original.len}, string = «««{s}»»»"
var previous = Rune(0)
var squeezed: seq[Rune]
for rune in original:
if rune != previous:
squeezed.add(rune)
previous = rune
elif rune != ch:
squeezed.add(rune)
echo fmt"Squeezed: length = {squeezed.len}, string = «««{squeezed}»»»"
echo ""
const 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",
"😍😀🙌💃😍😍😍🙌",]
const Chars = [@[Rune(' ')], @[Rune('-')], @[Rune('7')], @[Rune('.')],
@[Rune(' '), Rune('-'), Rune('r')],
@[Rune('e')], @[Rune('s')], @[Rune('a')], "😍".toRunes]
for i, s in Strings:
for ch in Chars[i]:
s.squeeze(ch)
| #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 this program in Java while keeping its functionality equivalent to the Nim version. | import unicode, strformat
proc squeeze(s: string; ch: Rune) =
echo fmt"Specified character: '{ch}'"
let original = s.toRunes
echo fmt"Original: length = {original.len}, string = «««{s}»»»"
var previous = Rune(0)
var squeezed: seq[Rune]
for rune in original:
if rune != previous:
squeezed.add(rune)
previous = rune
elif rune != ch:
squeezed.add(rune)
echo fmt"Squeezed: length = {squeezed.len}, string = «««{squeezed}»»»"
echo ""
const 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",
"😍😀🙌💃😍😍😍🙌",]
const Chars = [@[Rune(' ')], @[Rune('-')], @[Rune('7')], @[Rune('.')],
@[Rune(' '), Rune('-'), Rune('r')],
@[Rune('e')], @[Rune('s')], @[Rune('a')], "😍".toRunes]
for i, s in Strings:
for ch in Chars[i]:
s.squeeze(ch)
|
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();
}
}
|
Maintain the same structure and functionality when rewriting this code in Java. | import unicode, strformat
proc squeeze(s: string; ch: Rune) =
echo fmt"Specified character: '{ch}'"
let original = s.toRunes
echo fmt"Original: length = {original.len}, string = «««{s}»»»"
var previous = Rune(0)
var squeezed: seq[Rune]
for rune in original:
if rune != previous:
squeezed.add(rune)
previous = rune
elif rune != ch:
squeezed.add(rune)
echo fmt"Squeezed: length = {squeezed.len}, string = «««{squeezed}»»»"
echo ""
const 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",
"😍😀🙌💃😍😍😍🙌",]
const Chars = [@[Rune(' ')], @[Rune('-')], @[Rune('7')], @[Rune('.')],
@[Rune(' '), Rune('-'), Rune('r')],
@[Rune('e')], @[Rune('s')], @[Rune('a')], "😍".toRunes]
for i, s in Strings:
for ch in Chars[i]:
s.squeeze(ch)
|
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();
}
}
|
Transform the following Nim implementation into Python, maintaining the same output and logic. | import unicode, strformat
proc squeeze(s: string; ch: Rune) =
echo fmt"Specified character: '{ch}'"
let original = s.toRunes
echo fmt"Original: length = {original.len}, string = «««{s}»»»"
var previous = Rune(0)
var squeezed: seq[Rune]
for rune in original:
if rune != previous:
squeezed.add(rune)
previous = rune
elif rune != ch:
squeezed.add(rune)
echo fmt"Squeezed: length = {squeezed.len}, string = «««{squeezed}»»»"
echo ""
const 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",
"😍😀🙌💃😍😍😍🙌",]
const Chars = [@[Rune(' ')], @[Rune('-')], @[Rune('7')], @[Rune('.')],
@[Rune(' '), Rune('-'), Rune('r')],
@[Rune('e')], @[Rune('s')], @[Rune('a')], "😍".toRunes]
for i, s in Strings:
for ch in Chars[i]:
s.squeeze(ch)
| 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 Nim to Python without modifying what it does. | import unicode, strformat
proc squeeze(s: string; ch: Rune) =
echo fmt"Specified character: '{ch}'"
let original = s.toRunes
echo fmt"Original: length = {original.len}, string = «««{s}»»»"
var previous = Rune(0)
var squeezed: seq[Rune]
for rune in original:
if rune != previous:
squeezed.add(rune)
previous = rune
elif rune != ch:
squeezed.add(rune)
echo fmt"Squeezed: length = {squeezed.len}, string = «««{squeezed}»»»"
echo ""
const 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",
"😍😀🙌💃😍😍😍🙌",]
const Chars = [@[Rune(' ')], @[Rune('-')], @[Rune('7')], @[Rune('.')],
@[Rune(' '), Rune('-'), Rune('r')],
@[Rune('e')], @[Rune('s')], @[Rune('a')], "😍".toRunes]
for i, s in Strings:
for ch in Chars[i]:
s.squeeze(ch)
| 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 Nim snippet to VB and keep its semantics consistent. | import unicode, strformat
proc squeeze(s: string; ch: Rune) =
echo fmt"Specified character: '{ch}'"
let original = s.toRunes
echo fmt"Original: length = {original.len}, string = «««{s}»»»"
var previous = Rune(0)
var squeezed: seq[Rune]
for rune in original:
if rune != previous:
squeezed.add(rune)
previous = rune
elif rune != ch:
squeezed.add(rune)
echo fmt"Squeezed: length = {squeezed.len}, string = «««{squeezed}»»»"
echo ""
const 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",
"😍😀🙌💃😍😍😍🙌",]
const Chars = [@[Rune(' ')], @[Rune('-')], @[Rune('7')], @[Rune('.')],
@[Rune(' '), Rune('-'), Rune('r')],
@[Rune('e')], @[Rune('s')], @[Rune('a')], "😍".toRunes]
for i, s in Strings:
for ch in Chars[i]:
s.squeeze(ch)
| 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
|
Transform the following Nim implementation into VB, maintaining the same output and logic. | import unicode, strformat
proc squeeze(s: string; ch: Rune) =
echo fmt"Specified character: '{ch}'"
let original = s.toRunes
echo fmt"Original: length = {original.len}, string = «««{s}»»»"
var previous = Rune(0)
var squeezed: seq[Rune]
for rune in original:
if rune != previous:
squeezed.add(rune)
previous = rune
elif rune != ch:
squeezed.add(rune)
echo fmt"Squeezed: length = {squeezed.len}, string = «««{squeezed}»»»"
echo ""
const 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",
"😍😀🙌💃😍😍😍🙌",]
const Chars = [@[Rune(' ')], @[Rune('-')], @[Rune('7')], @[Rune('.')],
@[Rune(' '), Rune('-'), Rune('r')],
@[Rune('e')], @[Rune('s')], @[Rune('a')], "😍".toRunes]
for i, s in Strings:
for ch in Chars[i]:
s.squeeze(ch)
| 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
|
Keep all operations the same but rewrite the snippet in Go. | import unicode, strformat
proc squeeze(s: string; ch: Rune) =
echo fmt"Specified character: '{ch}'"
let original = s.toRunes
echo fmt"Original: length = {original.len}, string = «««{s}»»»"
var previous = Rune(0)
var squeezed: seq[Rune]
for rune in original:
if rune != previous:
squeezed.add(rune)
previous = rune
elif rune != ch:
squeezed.add(rune)
echo fmt"Squeezed: length = {squeezed.len}, string = «««{squeezed}»»»"
echo ""
const 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",
"😍😀🙌💃😍😍😍🙌",]
const Chars = [@[Rune(' ')], @[Rune('-')], @[Rune('7')], @[Rune('.')],
@[Rune(' '), Rune('-'), Rune('r')],
@[Rune('e')], @[Rune('s')], @[Rune('a')], "😍".toRunes]
for i, s in Strings:
for ch in Chars[i]:
s.squeeze(ch)
| 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 Go instead of Nim, keeping it the same logically? | import unicode, strformat
proc squeeze(s: string; ch: Rune) =
echo fmt"Specified character: '{ch}'"
let original = s.toRunes
echo fmt"Original: length = {original.len}, string = «««{s}»»»"
var previous = Rune(0)
var squeezed: seq[Rune]
for rune in original:
if rune != previous:
squeezed.add(rune)
previous = rune
elif rune != ch:
squeezed.add(rune)
echo fmt"Squeezed: length = {squeezed.len}, string = «««{squeezed}»»»"
echo ""
const 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",
"😍😀🙌💃😍😍😍🙌",]
const Chars = [@[Rune(' ')], @[Rune('-')], @[Rune('7')], @[Rune('.')],
@[Rune(' '), Rune('-'), Rune('r')],
@[Rune('e')], @[Rune('s')], @[Rune('a')], "😍".toRunes]
for i, s in Strings:
for ch in Chars[i]:
s.squeeze(ch)
| 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)
}
}
}
|
Produce a functionally identical C code for the snippet given in Perl. | use strict;
use warnings;
use Unicode::UCD 'charinfo';
for (
['', ' '],
['"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']
) {
my($phrase,$char) = @$_;
(my $squeeze = $phrase) =~ s/([$char])\1+/$1/g;
printf "\nOriginal length: %d <<<%s>>>\nSqueezable on \"%s\": %s\nSqueezed length: %d <<<%s>>>\n",
length($phrase), $phrase,
charinfo(ord $char)->{'name'},
$phrase ne $squeeze ? 'True' : 'False',
length($squeeze), $squeeze
}
| #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 Perl code in C. | use strict;
use warnings;
use Unicode::UCD 'charinfo';
for (
['', ' '],
['"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']
) {
my($phrase,$char) = @$_;
(my $squeeze = $phrase) =~ s/([$char])\1+/$1/g;
printf "\nOriginal length: %d <<<%s>>>\nSqueezable on \"%s\": %s\nSqueezed length: %d <<<%s>>>\n",
length($phrase), $phrase,
charinfo(ord $char)->{'name'},
$phrase ne $squeeze ? 'True' : 'False',
length($squeeze), $squeeze
}
| #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 Perl version. | use strict;
use warnings;
use Unicode::UCD 'charinfo';
for (
['', ' '],
['"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']
) {
my($phrase,$char) = @$_;
(my $squeeze = $phrase) =~ s/([$char])\1+/$1/g;
printf "\nOriginal length: %d <<<%s>>>\nSqueezable on \"%s\": %s\nSqueezed length: %d <<<%s>>>\n",
length($phrase), $phrase,
charinfo(ord $char)->{'name'},
$phrase ne $squeeze ? 'True' : 'False',
length($squeeze), $squeeze
}
| 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 Perl to C# with equivalent syntax and logic. | use strict;
use warnings;
use Unicode::UCD 'charinfo';
for (
['', ' '],
['"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']
) {
my($phrase,$char) = @$_;
(my $squeeze = $phrase) =~ s/([$char])\1+/$1/g;
printf "\nOriginal length: %d <<<%s>>>\nSqueezable on \"%s\": %s\nSqueezed length: %d <<<%s>>>\n",
length($phrase), $phrase,
charinfo(ord $char)->{'name'},
$phrase ne $squeeze ? 'True' : 'False',
length($squeeze), $squeeze
}
| 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 Perl block to C++, preserving its control flow and logic. | use strict;
use warnings;
use Unicode::UCD 'charinfo';
for (
['', ' '],
['"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']
) {
my($phrase,$char) = @$_;
(my $squeeze = $phrase) =~ s/([$char])\1+/$1/g;
printf "\nOriginal length: %d <<<%s>>>\nSqueezable on \"%s\": %s\nSqueezed length: %d <<<%s>>>\n",
length($phrase), $phrase,
charinfo(ord $char)->{'name'},
$phrase ne $squeeze ? 'True' : 'False',
length($squeeze), $squeeze
}
| #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 Perl snippet to C++ and keep its semantics consistent. | use strict;
use warnings;
use Unicode::UCD 'charinfo';
for (
['', ' '],
['"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']
) {
my($phrase,$char) = @$_;
(my $squeeze = $phrase) =~ s/([$char])\1+/$1/g;
printf "\nOriginal length: %d <<<%s>>>\nSqueezable on \"%s\": %s\nSqueezed length: %d <<<%s>>>\n",
length($phrase), $phrase,
charinfo(ord $char)->{'name'},
$phrase ne $squeeze ? 'True' : 'False',
length($squeeze), $squeeze
}
| #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;
}
|
Translate the given Perl code snippet into Java without altering its behavior. | use strict;
use warnings;
use Unicode::UCD 'charinfo';
for (
['', ' '],
['"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']
) {
my($phrase,$char) = @$_;
(my $squeeze = $phrase) =~ s/([$char])\1+/$1/g;
printf "\nOriginal length: %d <<<%s>>>\nSqueezable on \"%s\": %s\nSqueezed length: %d <<<%s>>>\n",
length($phrase), $phrase,
charinfo(ord $char)->{'name'},
$phrase ne $squeeze ? 'True' : 'False',
length($squeeze), $squeeze
}
|
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 Perl snippet to Java and keep its semantics consistent. | use strict;
use warnings;
use Unicode::UCD 'charinfo';
for (
['', ' '],
['"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']
) {
my($phrase,$char) = @$_;
(my $squeeze = $phrase) =~ s/([$char])\1+/$1/g;
printf "\nOriginal length: %d <<<%s>>>\nSqueezable on \"%s\": %s\nSqueezed length: %d <<<%s>>>\n",
length($phrase), $phrase,
charinfo(ord $char)->{'name'},
$phrase ne $squeeze ? 'True' : 'False',
length($squeeze), $squeeze
}
|
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 Perl. | use strict;
use warnings;
use Unicode::UCD 'charinfo';
for (
['', ' '],
['"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']
) {
my($phrase,$char) = @$_;
(my $squeeze = $phrase) =~ s/([$char])\1+/$1/g;
printf "\nOriginal length: %d <<<%s>>>\nSqueezable on \"%s\": %s\nSqueezed length: %d <<<%s>>>\n",
length($phrase), $phrase,
charinfo(ord $char)->{'name'},
$phrase ne $squeeze ? 'True' : 'False',
length($squeeze), $squeeze
}
| 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 Perl. | use strict;
use warnings;
use Unicode::UCD 'charinfo';
for (
['', ' '],
['"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']
) {
my($phrase,$char) = @$_;
(my $squeeze = $phrase) =~ s/([$char])\1+/$1/g;
printf "\nOriginal length: %d <<<%s>>>\nSqueezable on \"%s\": %s\nSqueezed length: %d <<<%s>>>\n",
length($phrase), $phrase,
charinfo(ord $char)->{'name'},
$phrase ne $squeeze ? 'True' : 'False',
length($squeeze), $squeeze
}
| 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 VB. | use strict;
use warnings;
use Unicode::UCD 'charinfo';
for (
['', ' '],
['"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']
) {
my($phrase,$char) = @$_;
(my $squeeze = $phrase) =~ s/([$char])\1+/$1/g;
printf "\nOriginal length: %d <<<%s>>>\nSqueezable on \"%s\": %s\nSqueezed length: %d <<<%s>>>\n",
length($phrase), $phrase,
charinfo(ord $char)->{'name'},
$phrase ne $squeeze ? 'True' : 'False',
length($squeeze), $squeeze
}
| 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
|
Keep all operations the same but rewrite the snippet in VB. | use strict;
use warnings;
use Unicode::UCD 'charinfo';
for (
['', ' '],
['"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']
) {
my($phrase,$char) = @$_;
(my $squeeze = $phrase) =~ s/([$char])\1+/$1/g;
printf "\nOriginal length: %d <<<%s>>>\nSqueezable on \"%s\": %s\nSqueezed length: %d <<<%s>>>\n",
length($phrase), $phrase,
charinfo(ord $char)->{'name'},
$phrase ne $squeeze ? 'True' : 'False',
length($squeeze), $squeeze
}
| 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 Perl code into Go without altering its purpose. | use strict;
use warnings;
use Unicode::UCD 'charinfo';
for (
['', ' '],
['"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']
) {
my($phrase,$char) = @$_;
(my $squeeze = $phrase) =~ s/([$char])\1+/$1/g;
printf "\nOriginal length: %d <<<%s>>>\nSqueezable on \"%s\": %s\nSqueezed length: %d <<<%s>>>\n",
length($phrase), $phrase,
charinfo(ord $char)->{'name'},
$phrase ne $squeeze ? 'True' : 'False',
length($squeeze), $squeeze
}
| 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 programming language of this snippet from Perl to Go without modifying what it does. | use strict;
use warnings;
use Unicode::UCD 'charinfo';
for (
['', ' '],
['"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']
) {
my($phrase,$char) = @$_;
(my $squeeze = $phrase) =~ s/([$char])\1+/$1/g;
printf "\nOriginal length: %d <<<%s>>>\nSqueezable on \"%s\": %s\nSqueezed length: %d <<<%s>>>\n",
length($phrase), $phrase,
charinfo(ord $char)->{'name'},
$phrase ne $squeeze ? 'True' : 'False',
length($squeeze), $squeeze
}
| 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)
}
}
}
|
Produce a functionally identical C code for the snippet given in R. | squeeze_string <- function(string, character){
str_iterable <- strsplit(string, "")[[1]]
message(paste0("Original String: ", "<<<", string, ">>>\n",
"Length: ", length(str_iterable), "\n",
"Character: ", character))
detect <- rep(TRUE, length(str_iterable))
for(i in 2:length(str_iterable)){
if(length(str_iterable) == 0) break
if(str_iterable[i] != character) next
if(str_iterable[i] == str_iterable[i-1])
detect[i] <- FALSE
}
squeezed_string <- paste(str_iterable[detect], collapse = "")
message(paste0("squeezed string: ", "<<<",squeezed_string, ">>>\n",
"Length: ", length(str_iterable[detect])), "\n")
}
squeeze_string("", " ")
squeeze_string("'If I were two-faced, would I be wearing this one?' --- Abraham Lincoln ", "-")
squeeze_string("..1111111111111111111111111111111111111111111111111111111111111117777888", "7")
squeeze_string("I never give 'em hell, I just tell the truth, and they think it's hell. ", ".")
squeeze_string(" --- Harry S Truman ", " ")
squeeze_string(" --- Harry S Truman ", "-")
squeeze_string(" --- Harry S Truman ", "r")
squeeze_string(" Ciao Mamma, guarda come mi diverto!!! ", "!")
| #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 R. | squeeze_string <- function(string, character){
str_iterable <- strsplit(string, "")[[1]]
message(paste0("Original String: ", "<<<", string, ">>>\n",
"Length: ", length(str_iterable), "\n",
"Character: ", character))
detect <- rep(TRUE, length(str_iterable))
for(i in 2:length(str_iterable)){
if(length(str_iterable) == 0) break
if(str_iterable[i] != character) next
if(str_iterable[i] == str_iterable[i-1])
detect[i] <- FALSE
}
squeezed_string <- paste(str_iterable[detect], collapse = "")
message(paste0("squeezed string: ", "<<<",squeezed_string, ">>>\n",
"Length: ", length(str_iterable[detect])), "\n")
}
squeeze_string("", " ")
squeeze_string("'If I were two-faced, would I be wearing this one?' --- Abraham Lincoln ", "-")
squeeze_string("..1111111111111111111111111111111111111111111111111111111111111117777888", "7")
squeeze_string("I never give 'em hell, I just tell the truth, and they think it's hell. ", ".")
squeeze_string(" --- Harry S Truman ", " ")
squeeze_string(" --- Harry S Truman ", "-")
squeeze_string(" --- Harry S Truman ", "r")
squeeze_string(" Ciao Mamma, guarda come mi diverto!!! ", "!")
| #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;
}
|
Keep all operations the same but rewrite the snippet in C#. | squeeze_string <- function(string, character){
str_iterable <- strsplit(string, "")[[1]]
message(paste0("Original String: ", "<<<", string, ">>>\n",
"Length: ", length(str_iterable), "\n",
"Character: ", character))
detect <- rep(TRUE, length(str_iterable))
for(i in 2:length(str_iterable)){
if(length(str_iterable) == 0) break
if(str_iterable[i] != character) next
if(str_iterable[i] == str_iterable[i-1])
detect[i] <- FALSE
}
squeezed_string <- paste(str_iterable[detect], collapse = "")
message(paste0("squeezed string: ", "<<<",squeezed_string, ">>>\n",
"Length: ", length(str_iterable[detect])), "\n")
}
squeeze_string("", " ")
squeeze_string("'If I were two-faced, would I be wearing this one?' --- Abraham Lincoln ", "-")
squeeze_string("..1111111111111111111111111111111111111111111111111111111111111117777888", "7")
squeeze_string("I never give 'em hell, I just tell the truth, and they think it's hell. ", ".")
squeeze_string(" --- Harry S Truman ", " ")
squeeze_string(" --- Harry S Truman ", "-")
squeeze_string(" --- Harry S Truman ", "r")
squeeze_string(" Ciao Mamma, guarda come mi diverto!!! ", "!")
| 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 R block to C#, preserving its control flow and logic. | squeeze_string <- function(string, character){
str_iterable <- strsplit(string, "")[[1]]
message(paste0("Original String: ", "<<<", string, ">>>\n",
"Length: ", length(str_iterable), "\n",
"Character: ", character))
detect <- rep(TRUE, length(str_iterable))
for(i in 2:length(str_iterable)){
if(length(str_iterable) == 0) break
if(str_iterable[i] != character) next
if(str_iterable[i] == str_iterable[i-1])
detect[i] <- FALSE
}
squeezed_string <- paste(str_iterable[detect], collapse = "")
message(paste0("squeezed string: ", "<<<",squeezed_string, ">>>\n",
"Length: ", length(str_iterable[detect])), "\n")
}
squeeze_string("", " ")
squeeze_string("'If I were two-faced, would I be wearing this one?' --- Abraham Lincoln ", "-")
squeeze_string("..1111111111111111111111111111111111111111111111111111111111111117777888", "7")
squeeze_string("I never give 'em hell, I just tell the truth, and they think it's hell. ", ".")
squeeze_string(" --- Harry S Truman ", " ")
squeeze_string(" --- Harry S Truman ", "-")
squeeze_string(" --- Harry S Truman ", "r")
squeeze_string(" Ciao Mamma, guarda come mi diverto!!! ", "!")
| 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 R to C++ without modifying what it does. | squeeze_string <- function(string, character){
str_iterable <- strsplit(string, "")[[1]]
message(paste0("Original String: ", "<<<", string, ">>>\n",
"Length: ", length(str_iterable), "\n",
"Character: ", character))
detect <- rep(TRUE, length(str_iterable))
for(i in 2:length(str_iterable)){
if(length(str_iterable) == 0) break
if(str_iterable[i] != character) next
if(str_iterable[i] == str_iterable[i-1])
detect[i] <- FALSE
}
squeezed_string <- paste(str_iterable[detect], collapse = "")
message(paste0("squeezed string: ", "<<<",squeezed_string, ">>>\n",
"Length: ", length(str_iterable[detect])), "\n")
}
squeeze_string("", " ")
squeeze_string("'If I were two-faced, would I be wearing this one?' --- Abraham Lincoln ", "-")
squeeze_string("..1111111111111111111111111111111111111111111111111111111111111117777888", "7")
squeeze_string("I never give 'em hell, I just tell the truth, and they think it's hell. ", ".")
squeeze_string(" --- Harry S Truman ", " ")
squeeze_string(" --- Harry S Truman ", "-")
squeeze_string(" --- Harry S Truman ", "r")
squeeze_string(" Ciao Mamma, guarda come mi diverto!!! ", "!")
| #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;
}
|
Port the provided R code into C++ while preserving the original functionality. | squeeze_string <- function(string, character){
str_iterable <- strsplit(string, "")[[1]]
message(paste0("Original String: ", "<<<", string, ">>>\n",
"Length: ", length(str_iterable), "\n",
"Character: ", character))
detect <- rep(TRUE, length(str_iterable))
for(i in 2:length(str_iterable)){
if(length(str_iterable) == 0) break
if(str_iterable[i] != character) next
if(str_iterable[i] == str_iterable[i-1])
detect[i] <- FALSE
}
squeezed_string <- paste(str_iterable[detect], collapse = "")
message(paste0("squeezed string: ", "<<<",squeezed_string, ">>>\n",
"Length: ", length(str_iterable[detect])), "\n")
}
squeeze_string("", " ")
squeeze_string("'If I were two-faced, would I be wearing this one?' --- Abraham Lincoln ", "-")
squeeze_string("..1111111111111111111111111111111111111111111111111111111111111117777888", "7")
squeeze_string("I never give 'em hell, I just tell the truth, and they think it's hell. ", ".")
squeeze_string(" --- Harry S Truman ", " ")
squeeze_string(" --- Harry S Truman ", "-")
squeeze_string(" --- Harry S Truman ", "r")
squeeze_string(" Ciao Mamma, guarda come mi diverto!!! ", "!")
| #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 code in Java as shown below in R. | squeeze_string <- function(string, character){
str_iterable <- strsplit(string, "")[[1]]
message(paste0("Original String: ", "<<<", string, ">>>\n",
"Length: ", length(str_iterable), "\n",
"Character: ", character))
detect <- rep(TRUE, length(str_iterable))
for(i in 2:length(str_iterable)){
if(length(str_iterable) == 0) break
if(str_iterable[i] != character) next
if(str_iterable[i] == str_iterable[i-1])
detect[i] <- FALSE
}
squeezed_string <- paste(str_iterable[detect], collapse = "")
message(paste0("squeezed string: ", "<<<",squeezed_string, ">>>\n",
"Length: ", length(str_iterable[detect])), "\n")
}
squeeze_string("", " ")
squeeze_string("'If I were two-faced, would I be wearing this one?' --- Abraham Lincoln ", "-")
squeeze_string("..1111111111111111111111111111111111111111111111111111111111111117777888", "7")
squeeze_string("I never give 'em hell, I just tell the truth, and they think it's hell. ", ".")
squeeze_string(" --- Harry S Truman ", " ")
squeeze_string(" --- Harry S Truman ", "-")
squeeze_string(" --- Harry S Truman ", "r")
squeeze_string(" Ciao Mamma, guarda come mi diverto!!! ", "!")
|
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 Java as shown below in R. | squeeze_string <- function(string, character){
str_iterable <- strsplit(string, "")[[1]]
message(paste0("Original String: ", "<<<", string, ">>>\n",
"Length: ", length(str_iterable), "\n",
"Character: ", character))
detect <- rep(TRUE, length(str_iterable))
for(i in 2:length(str_iterable)){
if(length(str_iterable) == 0) break
if(str_iterable[i] != character) next
if(str_iterable[i] == str_iterable[i-1])
detect[i] <- FALSE
}
squeezed_string <- paste(str_iterable[detect], collapse = "")
message(paste0("squeezed string: ", "<<<",squeezed_string, ">>>\n",
"Length: ", length(str_iterable[detect])), "\n")
}
squeeze_string("", " ")
squeeze_string("'If I were two-faced, would I be wearing this one?' --- Abraham Lincoln ", "-")
squeeze_string("..1111111111111111111111111111111111111111111111111111111111111117777888", "7")
squeeze_string("I never give 'em hell, I just tell the truth, and they think it's hell. ", ".")
squeeze_string(" --- Harry S Truman ", " ")
squeeze_string(" --- Harry S Truman ", "-")
squeeze_string(" --- Harry S Truman ", "r")
squeeze_string(" Ciao Mamma, guarda come mi diverto!!! ", "!")
|
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 the following code from R to Python, ensuring the logic remains intact. | squeeze_string <- function(string, character){
str_iterable <- strsplit(string, "")[[1]]
message(paste0("Original String: ", "<<<", string, ">>>\n",
"Length: ", length(str_iterable), "\n",
"Character: ", character))
detect <- rep(TRUE, length(str_iterable))
for(i in 2:length(str_iterable)){
if(length(str_iterable) == 0) break
if(str_iterable[i] != character) next
if(str_iterable[i] == str_iterable[i-1])
detect[i] <- FALSE
}
squeezed_string <- paste(str_iterable[detect], collapse = "")
message(paste0("squeezed string: ", "<<<",squeezed_string, ">>>\n",
"Length: ", length(str_iterable[detect])), "\n")
}
squeeze_string("", " ")
squeeze_string("'If I were two-faced, would I be wearing this one?' --- Abraham Lincoln ", "-")
squeeze_string("..1111111111111111111111111111111111111111111111111111111111111117777888", "7")
squeeze_string("I never give 'em hell, I just tell the truth, and they think it's hell. ", ".")
squeeze_string(" --- Harry S Truman ", " ")
squeeze_string(" --- Harry S Truman ", "-")
squeeze_string(" --- Harry S Truman ", "r")
squeeze_string(" Ciao Mamma, guarda come mi diverto!!! ", "!")
| 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 R. | squeeze_string <- function(string, character){
str_iterable <- strsplit(string, "")[[1]]
message(paste0("Original String: ", "<<<", string, ">>>\n",
"Length: ", length(str_iterable), "\n",
"Character: ", character))
detect <- rep(TRUE, length(str_iterable))
for(i in 2:length(str_iterable)){
if(length(str_iterable) == 0) break
if(str_iterable[i] != character) next
if(str_iterable[i] == str_iterable[i-1])
detect[i] <- FALSE
}
squeezed_string <- paste(str_iterable[detect], collapse = "")
message(paste0("squeezed string: ", "<<<",squeezed_string, ">>>\n",
"Length: ", length(str_iterable[detect])), "\n")
}
squeeze_string("", " ")
squeeze_string("'If I were two-faced, would I be wearing this one?' --- Abraham Lincoln ", "-")
squeeze_string("..1111111111111111111111111111111111111111111111111111111111111117777888", "7")
squeeze_string("I never give 'em hell, I just tell the truth, and they think it's hell. ", ".")
squeeze_string(" --- Harry S Truman ", " ")
squeeze_string(" --- Harry S Truman ", "-")
squeeze_string(" --- Harry S Truman ", "r")
squeeze_string(" Ciao Mamma, guarda come mi diverto!!! ", "!")
| 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}»»»" )
|
Port the provided R code into VB while preserving the original functionality. | squeeze_string <- function(string, character){
str_iterable <- strsplit(string, "")[[1]]
message(paste0("Original String: ", "<<<", string, ">>>\n",
"Length: ", length(str_iterable), "\n",
"Character: ", character))
detect <- rep(TRUE, length(str_iterable))
for(i in 2:length(str_iterable)){
if(length(str_iterable) == 0) break
if(str_iterable[i] != character) next
if(str_iterable[i] == str_iterable[i-1])
detect[i] <- FALSE
}
squeezed_string <- paste(str_iterable[detect], collapse = "")
message(paste0("squeezed string: ", "<<<",squeezed_string, ">>>\n",
"Length: ", length(str_iterable[detect])), "\n")
}
squeeze_string("", " ")
squeeze_string("'If I were two-faced, would I be wearing this one?' --- Abraham Lincoln ", "-")
squeeze_string("..1111111111111111111111111111111111111111111111111111111111111117777888", "7")
squeeze_string("I never give 'em hell, I just tell the truth, and they think it's hell. ", ".")
squeeze_string(" --- Harry S Truman ", " ")
squeeze_string(" --- Harry S Truman ", "-")
squeeze_string(" --- Harry S Truman ", "r")
squeeze_string(" Ciao Mamma, guarda come mi diverto!!! ", "!")
| 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
|
Generate a VB translation of this R snippet without changing its computational steps. | squeeze_string <- function(string, character){
str_iterable <- strsplit(string, "")[[1]]
message(paste0("Original String: ", "<<<", string, ">>>\n",
"Length: ", length(str_iterable), "\n",
"Character: ", character))
detect <- rep(TRUE, length(str_iterable))
for(i in 2:length(str_iterable)){
if(length(str_iterable) == 0) break
if(str_iterable[i] != character) next
if(str_iterable[i] == str_iterable[i-1])
detect[i] <- FALSE
}
squeezed_string <- paste(str_iterable[detect], collapse = "")
message(paste0("squeezed string: ", "<<<",squeezed_string, ">>>\n",
"Length: ", length(str_iterable[detect])), "\n")
}
squeeze_string("", " ")
squeeze_string("'If I were two-faced, would I be wearing this one?' --- Abraham Lincoln ", "-")
squeeze_string("..1111111111111111111111111111111111111111111111111111111111111117777888", "7")
squeeze_string("I never give 'em hell, I just tell the truth, and they think it's hell. ", ".")
squeeze_string(" --- Harry S Truman ", " ")
squeeze_string(" --- Harry S Truman ", "-")
squeeze_string(" --- Harry S Truman ", "r")
squeeze_string(" Ciao Mamma, guarda come mi diverto!!! ", "!")
| 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 R code snippet into Go without altering its behavior. | squeeze_string <- function(string, character){
str_iterable <- strsplit(string, "")[[1]]
message(paste0("Original String: ", "<<<", string, ">>>\n",
"Length: ", length(str_iterable), "\n",
"Character: ", character))
detect <- rep(TRUE, length(str_iterable))
for(i in 2:length(str_iterable)){
if(length(str_iterable) == 0) break
if(str_iterable[i] != character) next
if(str_iterable[i] == str_iterable[i-1])
detect[i] <- FALSE
}
squeezed_string <- paste(str_iterable[detect], collapse = "")
message(paste0("squeezed string: ", "<<<",squeezed_string, ">>>\n",
"Length: ", length(str_iterable[detect])), "\n")
}
squeeze_string("", " ")
squeeze_string("'If I were two-faced, would I be wearing this one?' --- Abraham Lincoln ", "-")
squeeze_string("..1111111111111111111111111111111111111111111111111111111111111117777888", "7")
squeeze_string("I never give 'em hell, I just tell the truth, and they think it's hell. ", ".")
squeeze_string(" --- Harry S Truman ", " ")
squeeze_string(" --- Harry S Truman ", "-")
squeeze_string(" --- Harry S Truman ", "r")
squeeze_string(" Ciao Mamma, guarda come mi diverto!!! ", "!")
| 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)
}
}
}
|
Please provide an equivalent version of this R code in Go. | squeeze_string <- function(string, character){
str_iterable <- strsplit(string, "")[[1]]
message(paste0("Original String: ", "<<<", string, ">>>\n",
"Length: ", length(str_iterable), "\n",
"Character: ", character))
detect <- rep(TRUE, length(str_iterable))
for(i in 2:length(str_iterable)){
if(length(str_iterable) == 0) break
if(str_iterable[i] != character) next
if(str_iterable[i] == str_iterable[i-1])
detect[i] <- FALSE
}
squeezed_string <- paste(str_iterable[detect], collapse = "")
message(paste0("squeezed string: ", "<<<",squeezed_string, ">>>\n",
"Length: ", length(str_iterable[detect])), "\n")
}
squeeze_string("", " ")
squeeze_string("'If I were two-faced, would I be wearing this one?' --- Abraham Lincoln ", "-")
squeeze_string("..1111111111111111111111111111111111111111111111111111111111111117777888", "7")
squeeze_string("I never give 'em hell, I just tell the truth, and they think it's hell. ", ".")
squeeze_string(" --- Harry S Truman ", " ")
squeeze_string(" --- Harry S Truman ", "-")
squeeze_string(" --- Harry S Truman ", "r")
squeeze_string(" Ciao Mamma, guarda come mi diverto!!! ", "!")
| 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 this program into C but keep the logic exactly as in Racket. | #lang racket/base
(define (squeeze-string s c)
(let loop ((cs (string->list s)) (squeezing? #f) (l 0) (acc null))
(cond [(null? cs) (values l (list->string (reverse acc)))]
[(and squeezing? (char=? (car cs) c)) (loop (cdr cs) #t l acc)]
[else (loop (cdr cs) (char=? (car cs) c) (add1 l) (cons (car cs) acc))])))
(define (report-squeeze s c)
(define-values (l′ s′) (squeeze-string s c))
(printf "Squeezing ~s in «««~a»»» (length ~a)~%" c s (string-length s))
(printf "Result: «««~a»»» (length ~a)~%~%" s′ l′))
(define (Determine-if-a-string-is-squeezeable)
(report-squeeze "" #\space)
(report-squeeze "\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln " #\-)
(report-squeeze "..1111111111111111111111111111111111111111111111111111111111111117777888" #\7)
(report-squeeze "I never give 'em hell, I just tell the truth, and they think it's hell. " #\.)
(define truman-sig " --- Harry S Truman ")
(report-squeeze truman-sig #\space)
(report-squeeze truman-sig #\-)
(report-squeeze truman-sig #\r))
(module+ main
(Determine-if-a-string-is-squeezeable))
| #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 a version of this Racket function in C with identical behavior. | #lang racket/base
(define (squeeze-string s c)
(let loop ((cs (string->list s)) (squeezing? #f) (l 0) (acc null))
(cond [(null? cs) (values l (list->string (reverse acc)))]
[(and squeezing? (char=? (car cs) c)) (loop (cdr cs) #t l acc)]
[else (loop (cdr cs) (char=? (car cs) c) (add1 l) (cons (car cs) acc))])))
(define (report-squeeze s c)
(define-values (l′ s′) (squeeze-string s c))
(printf "Squeezing ~s in «««~a»»» (length ~a)~%" c s (string-length s))
(printf "Result: «««~a»»» (length ~a)~%~%" s′ l′))
(define (Determine-if-a-string-is-squeezeable)
(report-squeeze "" #\space)
(report-squeeze "\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln " #\-)
(report-squeeze "..1111111111111111111111111111111111111111111111111111111111111117777888" #\7)
(report-squeeze "I never give 'em hell, I just tell the truth, and they think it's hell. " #\.)
(define truman-sig " --- Harry S Truman ")
(report-squeeze truman-sig #\space)
(report-squeeze truman-sig #\-)
(report-squeeze truman-sig #\r))
(module+ main
(Determine-if-a-string-is-squeezeable))
| #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 Racket implementation. | #lang racket/base
(define (squeeze-string s c)
(let loop ((cs (string->list s)) (squeezing? #f) (l 0) (acc null))
(cond [(null? cs) (values l (list->string (reverse acc)))]
[(and squeezing? (char=? (car cs) c)) (loop (cdr cs) #t l acc)]
[else (loop (cdr cs) (char=? (car cs) c) (add1 l) (cons (car cs) acc))])))
(define (report-squeeze s c)
(define-values (l′ s′) (squeeze-string s c))
(printf "Squeezing ~s in «««~a»»» (length ~a)~%" c s (string-length s))
(printf "Result: «««~a»»» (length ~a)~%~%" s′ l′))
(define (Determine-if-a-string-is-squeezeable)
(report-squeeze "" #\space)
(report-squeeze "\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln " #\-)
(report-squeeze "..1111111111111111111111111111111111111111111111111111111111111117777888" #\7)
(report-squeeze "I never give 'em hell, I just tell the truth, and they think it's hell. " #\.)
(define truman-sig " --- Harry S Truman ")
(report-squeeze truman-sig #\space)
(report-squeeze truman-sig #\-)
(report-squeeze truman-sig #\r))
(module+ main
(Determine-if-a-string-is-squeezeable))
| 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());
}
|
Please provide an equivalent version of this Racket code in C#. | #lang racket/base
(define (squeeze-string s c)
(let loop ((cs (string->list s)) (squeezing? #f) (l 0) (acc null))
(cond [(null? cs) (values l (list->string (reverse acc)))]
[(and squeezing? (char=? (car cs) c)) (loop (cdr cs) #t l acc)]
[else (loop (cdr cs) (char=? (car cs) c) (add1 l) (cons (car cs) acc))])))
(define (report-squeeze s c)
(define-values (l′ s′) (squeeze-string s c))
(printf "Squeezing ~s in «««~a»»» (length ~a)~%" c s (string-length s))
(printf "Result: «««~a»»» (length ~a)~%~%" s′ l′))
(define (Determine-if-a-string-is-squeezeable)
(report-squeeze "" #\space)
(report-squeeze "\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln " #\-)
(report-squeeze "..1111111111111111111111111111111111111111111111111111111111111117777888" #\7)
(report-squeeze "I never give 'em hell, I just tell the truth, and they think it's hell. " #\.)
(define truman-sig " --- Harry S Truman ")
(report-squeeze truman-sig #\space)
(report-squeeze truman-sig #\-)
(report-squeeze truman-sig #\r))
(module+ main
(Determine-if-a-string-is-squeezeable))
| 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 provided Racket code into C++ while preserving the original functionality. | #lang racket/base
(define (squeeze-string s c)
(let loop ((cs (string->list s)) (squeezing? #f) (l 0) (acc null))
(cond [(null? cs) (values l (list->string (reverse acc)))]
[(and squeezing? (char=? (car cs) c)) (loop (cdr cs) #t l acc)]
[else (loop (cdr cs) (char=? (car cs) c) (add1 l) (cons (car cs) acc))])))
(define (report-squeeze s c)
(define-values (l′ s′) (squeeze-string s c))
(printf "Squeezing ~s in «««~a»»» (length ~a)~%" c s (string-length s))
(printf "Result: «««~a»»» (length ~a)~%~%" s′ l′))
(define (Determine-if-a-string-is-squeezeable)
(report-squeeze "" #\space)
(report-squeeze "\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln " #\-)
(report-squeeze "..1111111111111111111111111111111111111111111111111111111111111117777888" #\7)
(report-squeeze "I never give 'em hell, I just tell the truth, and they think it's hell. " #\.)
(define truman-sig " --- Harry S Truman ")
(report-squeeze truman-sig #\space)
(report-squeeze truman-sig #\-)
(report-squeeze truman-sig #\r))
(module+ main
(Determine-if-a-string-is-squeezeable))
| #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 C++. | #lang racket/base
(define (squeeze-string s c)
(let loop ((cs (string->list s)) (squeezing? #f) (l 0) (acc null))
(cond [(null? cs) (values l (list->string (reverse acc)))]
[(and squeezing? (char=? (car cs) c)) (loop (cdr cs) #t l acc)]
[else (loop (cdr cs) (char=? (car cs) c) (add1 l) (cons (car cs) acc))])))
(define (report-squeeze s c)
(define-values (l′ s′) (squeeze-string s c))
(printf "Squeezing ~s in «««~a»»» (length ~a)~%" c s (string-length s))
(printf "Result: «««~a»»» (length ~a)~%~%" s′ l′))
(define (Determine-if-a-string-is-squeezeable)
(report-squeeze "" #\space)
(report-squeeze "\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln " #\-)
(report-squeeze "..1111111111111111111111111111111111111111111111111111111111111117777888" #\7)
(report-squeeze "I never give 'em hell, I just tell the truth, and they think it's hell. " #\.)
(define truman-sig " --- Harry S Truman ")
(report-squeeze truman-sig #\space)
(report-squeeze truman-sig #\-)
(report-squeeze truman-sig #\r))
(module+ main
(Determine-if-a-string-is-squeezeable))
| #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 this program in Java while keeping its functionality equivalent to the Racket version. | #lang racket/base
(define (squeeze-string s c)
(let loop ((cs (string->list s)) (squeezing? #f) (l 0) (acc null))
(cond [(null? cs) (values l (list->string (reverse acc)))]
[(and squeezing? (char=? (car cs) c)) (loop (cdr cs) #t l acc)]
[else (loop (cdr cs) (char=? (car cs) c) (add1 l) (cons (car cs) acc))])))
(define (report-squeeze s c)
(define-values (l′ s′) (squeeze-string s c))
(printf "Squeezing ~s in «««~a»»» (length ~a)~%" c s (string-length s))
(printf "Result: «««~a»»» (length ~a)~%~%" s′ l′))
(define (Determine-if-a-string-is-squeezeable)
(report-squeeze "" #\space)
(report-squeeze "\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln " #\-)
(report-squeeze "..1111111111111111111111111111111111111111111111111111111111111117777888" #\7)
(report-squeeze "I never give 'em hell, I just tell the truth, and they think it's hell. " #\.)
(define truman-sig " --- Harry S Truman ")
(report-squeeze truman-sig #\space)
(report-squeeze truman-sig #\-)
(report-squeeze truman-sig #\r))
(module+ main
(Determine-if-a-string-is-squeezeable))
|
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();
}
}
|
Generate an equivalent Java version of this Racket code. | #lang racket/base
(define (squeeze-string s c)
(let loop ((cs (string->list s)) (squeezing? #f) (l 0) (acc null))
(cond [(null? cs) (values l (list->string (reverse acc)))]
[(and squeezing? (char=? (car cs) c)) (loop (cdr cs) #t l acc)]
[else (loop (cdr cs) (char=? (car cs) c) (add1 l) (cons (car cs) acc))])))
(define (report-squeeze s c)
(define-values (l′ s′) (squeeze-string s c))
(printf "Squeezing ~s in «««~a»»» (length ~a)~%" c s (string-length s))
(printf "Result: «««~a»»» (length ~a)~%~%" s′ l′))
(define (Determine-if-a-string-is-squeezeable)
(report-squeeze "" #\space)
(report-squeeze "\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln " #\-)
(report-squeeze "..1111111111111111111111111111111111111111111111111111111111111117777888" #\7)
(report-squeeze "I never give 'em hell, I just tell the truth, and they think it's hell. " #\.)
(define truman-sig " --- Harry S Truman ")
(report-squeeze truman-sig #\space)
(report-squeeze truman-sig #\-)
(report-squeeze truman-sig #\r))
(module+ main
(Determine-if-a-string-is-squeezeable))
|
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();
}
}
|
Transform the following Racket implementation into Python, maintaining the same output and logic. | #lang racket/base
(define (squeeze-string s c)
(let loop ((cs (string->list s)) (squeezing? #f) (l 0) (acc null))
(cond [(null? cs) (values l (list->string (reverse acc)))]
[(and squeezing? (char=? (car cs) c)) (loop (cdr cs) #t l acc)]
[else (loop (cdr cs) (char=? (car cs) c) (add1 l) (cons (car cs) acc))])))
(define (report-squeeze s c)
(define-values (l′ s′) (squeeze-string s c))
(printf "Squeezing ~s in «««~a»»» (length ~a)~%" c s (string-length s))
(printf "Result: «««~a»»» (length ~a)~%~%" s′ l′))
(define (Determine-if-a-string-is-squeezeable)
(report-squeeze "" #\space)
(report-squeeze "\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln " #\-)
(report-squeeze "..1111111111111111111111111111111111111111111111111111111111111117777888" #\7)
(report-squeeze "I never give 'em hell, I just tell the truth, and they think it's hell. " #\.)
(define truman-sig " --- Harry S Truman ")
(report-squeeze truman-sig #\space)
(report-squeeze truman-sig #\-)
(report-squeeze truman-sig #\r))
(module+ main
(Determine-if-a-string-is-squeezeable))
| 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 Python translation of this Racket snippet without changing its computational steps. | #lang racket/base
(define (squeeze-string s c)
(let loop ((cs (string->list s)) (squeezing? #f) (l 0) (acc null))
(cond [(null? cs) (values l (list->string (reverse acc)))]
[(and squeezing? (char=? (car cs) c)) (loop (cdr cs) #t l acc)]
[else (loop (cdr cs) (char=? (car cs) c) (add1 l) (cons (car cs) acc))])))
(define (report-squeeze s c)
(define-values (l′ s′) (squeeze-string s c))
(printf "Squeezing ~s in «««~a»»» (length ~a)~%" c s (string-length s))
(printf "Result: «««~a»»» (length ~a)~%~%" s′ l′))
(define (Determine-if-a-string-is-squeezeable)
(report-squeeze "" #\space)
(report-squeeze "\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln " #\-)
(report-squeeze "..1111111111111111111111111111111111111111111111111111111111111117777888" #\7)
(report-squeeze "I never give 'em hell, I just tell the truth, and they think it's hell. " #\.)
(define truman-sig " --- Harry S Truman ")
(report-squeeze truman-sig #\space)
(report-squeeze truman-sig #\-)
(report-squeeze truman-sig #\r))
(module+ main
(Determine-if-a-string-is-squeezeable))
| 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 Racket. | #lang racket/base
(define (squeeze-string s c)
(let loop ((cs (string->list s)) (squeezing? #f) (l 0) (acc null))
(cond [(null? cs) (values l (list->string (reverse acc)))]
[(and squeezing? (char=? (car cs) c)) (loop (cdr cs) #t l acc)]
[else (loop (cdr cs) (char=? (car cs) c) (add1 l) (cons (car cs) acc))])))
(define (report-squeeze s c)
(define-values (l′ s′) (squeeze-string s c))
(printf "Squeezing ~s in «««~a»»» (length ~a)~%" c s (string-length s))
(printf "Result: «««~a»»» (length ~a)~%~%" s′ l′))
(define (Determine-if-a-string-is-squeezeable)
(report-squeeze "" #\space)
(report-squeeze "\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln " #\-)
(report-squeeze "..1111111111111111111111111111111111111111111111111111111111111117777888" #\7)
(report-squeeze "I never give 'em hell, I just tell the truth, and they think it's hell. " #\.)
(define truman-sig " --- Harry S Truman ")
(report-squeeze truman-sig #\space)
(report-squeeze truman-sig #\-)
(report-squeeze truman-sig #\r))
(module+ main
(Determine-if-a-string-is-squeezeable))
| 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 Racket snippet. | #lang racket/base
(define (squeeze-string s c)
(let loop ((cs (string->list s)) (squeezing? #f) (l 0) (acc null))
(cond [(null? cs) (values l (list->string (reverse acc)))]
[(and squeezing? (char=? (car cs) c)) (loop (cdr cs) #t l acc)]
[else (loop (cdr cs) (char=? (car cs) c) (add1 l) (cons (car cs) acc))])))
(define (report-squeeze s c)
(define-values (l′ s′) (squeeze-string s c))
(printf "Squeezing ~s in «««~a»»» (length ~a)~%" c s (string-length s))
(printf "Result: «««~a»»» (length ~a)~%~%" s′ l′))
(define (Determine-if-a-string-is-squeezeable)
(report-squeeze "" #\space)
(report-squeeze "\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln " #\-)
(report-squeeze "..1111111111111111111111111111111111111111111111111111111111111117777888" #\7)
(report-squeeze "I never give 'em hell, I just tell the truth, and they think it's hell. " #\.)
(define truman-sig " --- Harry S Truman ")
(report-squeeze truman-sig #\space)
(report-squeeze truman-sig #\-)
(report-squeeze truman-sig #\r))
(module+ main
(Determine-if-a-string-is-squeezeable))
| 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
|
Keep all operations the same but rewrite the snippet in Go. | #lang racket/base
(define (squeeze-string s c)
(let loop ((cs (string->list s)) (squeezing? #f) (l 0) (acc null))
(cond [(null? cs) (values l (list->string (reverse acc)))]
[(and squeezing? (char=? (car cs) c)) (loop (cdr cs) #t l acc)]
[else (loop (cdr cs) (char=? (car cs) c) (add1 l) (cons (car cs) acc))])))
(define (report-squeeze s c)
(define-values (l′ s′) (squeeze-string s c))
(printf "Squeezing ~s in «««~a»»» (length ~a)~%" c s (string-length s))
(printf "Result: «««~a»»» (length ~a)~%~%" s′ l′))
(define (Determine-if-a-string-is-squeezeable)
(report-squeeze "" #\space)
(report-squeeze "\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln " #\-)
(report-squeeze "..1111111111111111111111111111111111111111111111111111111111111117777888" #\7)
(report-squeeze "I never give 'em hell, I just tell the truth, and they think it's hell. " #\.)
(define truman-sig " --- Harry S Truman ")
(report-squeeze truman-sig #\space)
(report-squeeze truman-sig #\-)
(report-squeeze truman-sig #\r))
(module+ main
(Determine-if-a-string-is-squeezeable))
| 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)
}
}
}
|
Maintain the same structure and functionality when rewriting this code in Go. | #lang racket/base
(define (squeeze-string s c)
(let loop ((cs (string->list s)) (squeezing? #f) (l 0) (acc null))
(cond [(null? cs) (values l (list->string (reverse acc)))]
[(and squeezing? (char=? (car cs) c)) (loop (cdr cs) #t l acc)]
[else (loop (cdr cs) (char=? (car cs) c) (add1 l) (cons (car cs) acc))])))
(define (report-squeeze s c)
(define-values (l′ s′) (squeeze-string s c))
(printf "Squeezing ~s in «««~a»»» (length ~a)~%" c s (string-length s))
(printf "Result: «««~a»»» (length ~a)~%~%" s′ l′))
(define (Determine-if-a-string-is-squeezeable)
(report-squeeze "" #\space)
(report-squeeze "\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln " #\-)
(report-squeeze "..1111111111111111111111111111111111111111111111111111111111111117777888" #\7)
(report-squeeze "I never give 'em hell, I just tell the truth, and they think it's hell. " #\.)
(define truman-sig " --- Harry S Truman ")
(report-squeeze truman-sig #\space)
(report-squeeze truman-sig #\-)
(report-squeeze truman-sig #\r))
(module+ main
(Determine-if-a-string-is-squeezeable))
| 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)
}
}
}
|
Maintain the same structure and functionality when rewriting this code in C. |
@.=
#.1= ' '; @.1=
#.2= '-'; @.2= '"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln '
#.3= '7'; @.3= ..1111111111111111111111111111111111111111111111111111111111111117777888
#.4= . ; @.4= "I never give 'em hell, I just tell the truth, and they think it's hell. "
#.5= ' '; @.5= ' --- Harry S Truman '
#.6= '-'; @.6= @.5
#.7= 'r'; @.7= @.5
do j=1; L= length(@.j)
say copies('═', 105)
if j>1 & L==0 then leave
say ' specified immediate repeatable character=' #.j " ('"c2x(#.j)"'x)"
say ' length='right(L, 3) " input=«««" || @.j || '»»»'
new= squeeze(@.j, #.j)
w= length(new)
say ' length='right(w, 3) " output=«««" || new || '»»»'
end
exit
squeeze: procedure; parse arg y 1 $ 2,z
if pos(z || z, y)==0 then return y
do k=2 to length(y)
_= substr(y, k, 1)
if _==right($, 1) & _==z then iterate
$= $ || _
end
return $
| #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;
}
|
Can you help me rewrite this code in C instead of REXX, keeping it the same logically? |
@.=
#.1= ' '; @.1=
#.2= '-'; @.2= '"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln '
#.3= '7'; @.3= ..1111111111111111111111111111111111111111111111111111111111111117777888
#.4= . ; @.4= "I never give 'em hell, I just tell the truth, and they think it's hell. "
#.5= ' '; @.5= ' --- Harry S Truman '
#.6= '-'; @.6= @.5
#.7= 'r'; @.7= @.5
do j=1; L= length(@.j)
say copies('═', 105)
if j>1 & L==0 then leave
say ' specified immediate repeatable character=' #.j " ('"c2x(#.j)"'x)"
say ' length='right(L, 3) " input=«««" || @.j || '»»»'
new= squeeze(@.j, #.j)
w= length(new)
say ' length='right(w, 3) " output=«««" || new || '»»»'
end
exit
squeeze: procedure; parse arg y 1 $ 2,z
if pos(z || z, y)==0 then return y
do k=2 to length(y)
_= substr(y, k, 1)
if _==right($, 1) & _==z then iterate
$= $ || _
end
return $
| #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 REXX snippet without changing its computational steps. |
@.=
#.1= ' '; @.1=
#.2= '-'; @.2= '"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln '
#.3= '7'; @.3= ..1111111111111111111111111111111111111111111111111111111111111117777888
#.4= . ; @.4= "I never give 'em hell, I just tell the truth, and they think it's hell. "
#.5= ' '; @.5= ' --- Harry S Truman '
#.6= '-'; @.6= @.5
#.7= 'r'; @.7= @.5
do j=1; L= length(@.j)
say copies('═', 105)
if j>1 & L==0 then leave
say ' specified immediate repeatable character=' #.j " ('"c2x(#.j)"'x)"
say ' length='right(L, 3) " input=«««" || @.j || '»»»'
new= squeeze(@.j, #.j)
w= length(new)
say ' length='right(w, 3) " output=«««" || new || '»»»'
end
exit
squeeze: procedure; parse arg y 1 $ 2,z
if pos(z || z, y)==0 then return y
do k=2 to length(y)
_= substr(y, k, 1)
if _==right($, 1) & _==z then iterate
$= $ || _
end
return $
| 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 REXX. |
@.=
#.1= ' '; @.1=
#.2= '-'; @.2= '"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln '
#.3= '7'; @.3= ..1111111111111111111111111111111111111111111111111111111111111117777888
#.4= . ; @.4= "I never give 'em hell, I just tell the truth, and they think it's hell. "
#.5= ' '; @.5= ' --- Harry S Truman '
#.6= '-'; @.6= @.5
#.7= 'r'; @.7= @.5
do j=1; L= length(@.j)
say copies('═', 105)
if j>1 & L==0 then leave
say ' specified immediate repeatable character=' #.j " ('"c2x(#.j)"'x)"
say ' length='right(L, 3) " input=«««" || @.j || '»»»'
new= squeeze(@.j, #.j)
w= length(new)
say ' length='right(w, 3) " output=«««" || new || '»»»'
end
exit
squeeze: procedure; parse arg y 1 $ 2,z
if pos(z || z, y)==0 then return y
do k=2 to length(y)
_= substr(y, k, 1)
if _==right($, 1) & _==z then iterate
$= $ || _
end
return $
| 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 REXX block to C++, preserving its control flow and logic. |
@.=
#.1= ' '; @.1=
#.2= '-'; @.2= '"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln '
#.3= '7'; @.3= ..1111111111111111111111111111111111111111111111111111111111111117777888
#.4= . ; @.4= "I never give 'em hell, I just tell the truth, and they think it's hell. "
#.5= ' '; @.5= ' --- Harry S Truman '
#.6= '-'; @.6= @.5
#.7= 'r'; @.7= @.5
do j=1; L= length(@.j)
say copies('═', 105)
if j>1 & L==0 then leave
say ' specified immediate repeatable character=' #.j " ('"c2x(#.j)"'x)"
say ' length='right(L, 3) " input=«««" || @.j || '»»»'
new= squeeze(@.j, #.j)
w= length(new)
say ' length='right(w, 3) " output=«««" || new || '»»»'
end
exit
squeeze: procedure; parse arg y 1 $ 2,z
if pos(z || z, y)==0 then return y
do k=2 to length(y)
_= substr(y, k, 1)
if _==right($, 1) & _==z then iterate
$= $ || _
end
return $
| #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 REXX implementation into C++, maintaining the same output and logic. |
@.=
#.1= ' '; @.1=
#.2= '-'; @.2= '"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln '
#.3= '7'; @.3= ..1111111111111111111111111111111111111111111111111111111111111117777888
#.4= . ; @.4= "I never give 'em hell, I just tell the truth, and they think it's hell. "
#.5= ' '; @.5= ' --- Harry S Truman '
#.6= '-'; @.6= @.5
#.7= 'r'; @.7= @.5
do j=1; L= length(@.j)
say copies('═', 105)
if j>1 & L==0 then leave
say ' specified immediate repeatable character=' #.j " ('"c2x(#.j)"'x)"
say ' length='right(L, 3) " input=«««" || @.j || '»»»'
new= squeeze(@.j, #.j)
w= length(new)
say ' length='right(w, 3) " output=«««" || new || '»»»'
end
exit
squeeze: procedure; parse arg y 1 $ 2,z
if pos(z || z, y)==0 then return y
do k=2 to length(y)
_= substr(y, k, 1)
if _==right($, 1) & _==z then iterate
$= $ || _
end
return $
| #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 the following code from REXX to Java, ensuring the logic remains intact. |
@.=
#.1= ' '; @.1=
#.2= '-'; @.2= '"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln '
#.3= '7'; @.3= ..1111111111111111111111111111111111111111111111111111111111111117777888
#.4= . ; @.4= "I never give 'em hell, I just tell the truth, and they think it's hell. "
#.5= ' '; @.5= ' --- Harry S Truman '
#.6= '-'; @.6= @.5
#.7= 'r'; @.7= @.5
do j=1; L= length(@.j)
say copies('═', 105)
if j>1 & L==0 then leave
say ' specified immediate repeatable character=' #.j " ('"c2x(#.j)"'x)"
say ' length='right(L, 3) " input=«««" || @.j || '»»»'
new= squeeze(@.j, #.j)
w= length(new)
say ' length='right(w, 3) " output=«««" || new || '»»»'
end
exit
squeeze: procedure; parse arg y 1 $ 2,z
if pos(z || z, y)==0 then return y
do k=2 to length(y)
_= substr(y, k, 1)
if _==right($, 1) & _==z then iterate
$= $ || _
end
return $
|
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 the given REXX code snippet into Java without altering its behavior. |
@.=
#.1= ' '; @.1=
#.2= '-'; @.2= '"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln '
#.3= '7'; @.3= ..1111111111111111111111111111111111111111111111111111111111111117777888
#.4= . ; @.4= "I never give 'em hell, I just tell the truth, and they think it's hell. "
#.5= ' '; @.5= ' --- Harry S Truman '
#.6= '-'; @.6= @.5
#.7= 'r'; @.7= @.5
do j=1; L= length(@.j)
say copies('═', 105)
if j>1 & L==0 then leave
say ' specified immediate repeatable character=' #.j " ('"c2x(#.j)"'x)"
say ' length='right(L, 3) " input=«««" || @.j || '»»»'
new= squeeze(@.j, #.j)
w= length(new)
say ' length='right(w, 3) " output=«««" || new || '»»»'
end
exit
squeeze: procedure; parse arg y 1 $ 2,z
if pos(z || z, y)==0 then return y
do k=2 to length(y)
_= substr(y, k, 1)
if _==right($, 1) & _==z then iterate
$= $ || _
end
return $
|
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 REXX code into Python without altering its purpose. |
@.=
#.1= ' '; @.1=
#.2= '-'; @.2= '"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln '
#.3= '7'; @.3= ..1111111111111111111111111111111111111111111111111111111111111117777888
#.4= . ; @.4= "I never give 'em hell, I just tell the truth, and they think it's hell. "
#.5= ' '; @.5= ' --- Harry S Truman '
#.6= '-'; @.6= @.5
#.7= 'r'; @.7= @.5
do j=1; L= length(@.j)
say copies('═', 105)
if j>1 & L==0 then leave
say ' specified immediate repeatable character=' #.j " ('"c2x(#.j)"'x)"
say ' length='right(L, 3) " input=«««" || @.j || '»»»'
new= squeeze(@.j, #.j)
w= length(new)
say ' length='right(w, 3) " output=«««" || new || '»»»'
end
exit
squeeze: procedure; parse arg y 1 $ 2,z
if pos(z || z, y)==0 then return y
do k=2 to length(y)
_= substr(y, k, 1)
if _==right($, 1) & _==z then iterate
$= $ || _
end
return $
| 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}»»»" )
|
Port the provided REXX code into Python while preserving the original functionality. |
@.=
#.1= ' '; @.1=
#.2= '-'; @.2= '"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln '
#.3= '7'; @.3= ..1111111111111111111111111111111111111111111111111111111111111117777888
#.4= . ; @.4= "I never give 'em hell, I just tell the truth, and they think it's hell. "
#.5= ' '; @.5= ' --- Harry S Truman '
#.6= '-'; @.6= @.5
#.7= 'r'; @.7= @.5
do j=1; L= length(@.j)
say copies('═', 105)
if j>1 & L==0 then leave
say ' specified immediate repeatable character=' #.j " ('"c2x(#.j)"'x)"
say ' length='right(L, 3) " input=«««" || @.j || '»»»'
new= squeeze(@.j, #.j)
w= length(new)
say ' length='right(w, 3) " output=«««" || new || '»»»'
end
exit
squeeze: procedure; parse arg y 1 $ 2,z
if pos(z || z, y)==0 then return y
do k=2 to length(y)
_= substr(y, k, 1)
if _==right($, 1) & _==z then iterate
$= $ || _
end
return $
| 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}»»»" )
|
Preserve the algorithm and functionality while converting the code from REXX to VB. |
@.=
#.1= ' '; @.1=
#.2= '-'; @.2= '"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln '
#.3= '7'; @.3= ..1111111111111111111111111111111111111111111111111111111111111117777888
#.4= . ; @.4= "I never give 'em hell, I just tell the truth, and they think it's hell. "
#.5= ' '; @.5= ' --- Harry S Truman '
#.6= '-'; @.6= @.5
#.7= 'r'; @.7= @.5
do j=1; L= length(@.j)
say copies('═', 105)
if j>1 & L==0 then leave
say ' specified immediate repeatable character=' #.j " ('"c2x(#.j)"'x)"
say ' length='right(L, 3) " input=«««" || @.j || '»»»'
new= squeeze(@.j, #.j)
w= length(new)
say ' length='right(w, 3) " output=«««" || new || '»»»'
end
exit
squeeze: procedure; parse arg y 1 $ 2,z
if pos(z || z, y)==0 then return y
do k=2 to length(y)
_= substr(y, k, 1)
if _==right($, 1) & _==z then iterate
$= $ || _
end
return $
| 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 REXX to VB, ensuring the logic remains intact. |
@.=
#.1= ' '; @.1=
#.2= '-'; @.2= '"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln '
#.3= '7'; @.3= ..1111111111111111111111111111111111111111111111111111111111111117777888
#.4= . ; @.4= "I never give 'em hell, I just tell the truth, and they think it's hell. "
#.5= ' '; @.5= ' --- Harry S Truman '
#.6= '-'; @.6= @.5
#.7= 'r'; @.7= @.5
do j=1; L= length(@.j)
say copies('═', 105)
if j>1 & L==0 then leave
say ' specified immediate repeatable character=' #.j " ('"c2x(#.j)"'x)"
say ' length='right(L, 3) " input=«««" || @.j || '»»»'
new= squeeze(@.j, #.j)
w= length(new)
say ' length='right(w, 3) " output=«««" || new || '»»»'
end
exit
squeeze: procedure; parse arg y 1 $ 2,z
if pos(z || z, y)==0 then return y
do k=2 to length(y)
_= substr(y, k, 1)
if _==right($, 1) & _==z then iterate
$= $ || _
end
return $
| 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 REXX code snippet into Go without altering its behavior. |
@.=
#.1= ' '; @.1=
#.2= '-'; @.2= '"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln '
#.3= '7'; @.3= ..1111111111111111111111111111111111111111111111111111111111111117777888
#.4= . ; @.4= "I never give 'em hell, I just tell the truth, and they think it's hell. "
#.5= ' '; @.5= ' --- Harry S Truman '
#.6= '-'; @.6= @.5
#.7= 'r'; @.7= @.5
do j=1; L= length(@.j)
say copies('═', 105)
if j>1 & L==0 then leave
say ' specified immediate repeatable character=' #.j " ('"c2x(#.j)"'x)"
say ' length='right(L, 3) " input=«««" || @.j || '»»»'
new= squeeze(@.j, #.j)
w= length(new)
say ' length='right(w, 3) " output=«««" || new || '»»»'
end
exit
squeeze: procedure; parse arg y 1 $ 2,z
if pos(z || z, y)==0 then return y
do k=2 to length(y)
_= substr(y, k, 1)
if _==right($, 1) & _==z then iterate
$= $ || _
end
return $
| 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. |
@.=
#.1= ' '; @.1=
#.2= '-'; @.2= '"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln '
#.3= '7'; @.3= ..1111111111111111111111111111111111111111111111111111111111111117777888
#.4= . ; @.4= "I never give 'em hell, I just tell the truth, and they think it's hell. "
#.5= ' '; @.5= ' --- Harry S Truman '
#.6= '-'; @.6= @.5
#.7= 'r'; @.7= @.5
do j=1; L= length(@.j)
say copies('═', 105)
if j>1 & L==0 then leave
say ' specified immediate repeatable character=' #.j " ('"c2x(#.j)"'x)"
say ' length='right(L, 3) " input=«««" || @.j || '»»»'
new= squeeze(@.j, #.j)
w= length(new)
say ' length='right(w, 3) " output=«««" || new || '»»»'
end
exit
squeeze: procedure; parse arg y 1 $ 2,z
if pos(z || z, y)==0 then return y
do k=2 to length(y)
_= substr(y, k, 1)
if _==right($, 1) & _==z then iterate
$= $ || _
end
return $
| 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 following code from Ruby to C with equivalent syntax and logic. | 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 ",
"😍😀🙌💃😍😍😍🙌",]
squeeze_these = ["", "-", "7", ".", " -r", "😍"]
strings.zip(squeeze_these).each do |str, st|
puts "original: «««
st.chars.each do |c|
ssq = str.squeeze(c)
puts "
end
puts
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;
}
|
Write the same algorithm in C as shown in this Ruby implementation. | 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 ",
"😍😀🙌💃😍😍😍🙌",]
squeeze_these = ["", "-", "7", ".", " -r", "😍"]
strings.zip(squeeze_these).each do |str, st|
puts "original: «««
st.chars.each do |c|
ssq = str.squeeze(c)
puts "
end
puts
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;
}
|
Preserve the algorithm and functionality while converting the code from Ruby to C#. | 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 ",
"😍😀🙌💃😍😍😍🙌",]
squeeze_these = ["", "-", "7", ".", " -r", "😍"]
strings.zip(squeeze_these).each do |str, st|
puts "original: «««
st.chars.each do |c|
ssq = str.squeeze(c)
puts "
end
puts
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());
}
|
Keep all operations the same but rewrite the snippet in C#. | 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 ",
"😍😀🙌💃😍😍😍🙌",]
squeeze_these = ["", "-", "7", ".", " -r", "😍"]
strings.zip(squeeze_these).each do |str, st|
puts "original: «««
st.chars.each do |c|
ssq = str.squeeze(c)
puts "
end
puts
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());
}
|
Transform the following Ruby implementation into C++, maintaining the same output and logic. | 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 ",
"😍😀🙌💃😍😍😍🙌",]
squeeze_these = ["", "-", "7", ".", " -r", "😍"]
strings.zip(squeeze_these).each do |str, st|
puts "original: «««
st.chars.each do |c|
ssq = str.squeeze(c)
puts "
end
puts
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;
}
|
Change the programming language of this snippet from Ruby to C++ without modifying what it does. | 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 ",
"😍😀🙌💃😍😍😍🙌",]
squeeze_these = ["", "-", "7", ".", " -r", "😍"]
strings.zip(squeeze_these).each do |str, st|
puts "original: «««
st.chars.each do |c|
ssq = str.squeeze(c)
puts "
end
puts
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;
}
|
Generate a Java translation of this Ruby snippet without changing its computational steps. | 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 ",
"😍😀🙌💃😍😍😍🙌",]
squeeze_these = ["", "-", "7", ".", " -r", "😍"]
strings.zip(squeeze_these).each do |str, st|
puts "original: «««
st.chars.each do |c|
ssq = str.squeeze(c)
puts "
end
puts
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 Ruby block to Java, preserving its control flow and logic. | 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 ",
"😍😀🙌💃😍😍😍🙌",]
squeeze_these = ["", "-", "7", ".", " -r", "😍"]
strings.zip(squeeze_these).each do |str, st|
puts "original: «««
st.chars.each do |c|
ssq = str.squeeze(c)
puts "
end
puts
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();
}
}
|
Write a version of this Ruby function in Python with identical behavior. | 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 ",
"😍😀🙌💃😍😍😍🙌",]
squeeze_these = ["", "-", "7", ".", " -r", "😍"]
strings.zip(squeeze_these).each do |str, st|
puts "original: «««
st.chars.each do |c|
ssq = str.squeeze(c)
puts "
end
puts
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}»»»" )
|
Transform the following Ruby implementation into Python, maintaining the same output and logic. | 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 ",
"😍😀🙌💃😍😍😍🙌",]
squeeze_these = ["", "-", "7", ".", " -r", "😍"]
strings.zip(squeeze_these).each do |str, st|
puts "original: «««
st.chars.each do |c|
ssq = str.squeeze(c)
puts "
end
puts
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}»»»" )
|
Port the provided Ruby code into VB while preserving the original functionality. | 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 ",
"😍😀🙌💃😍😍😍🙌",]
squeeze_these = ["", "-", "7", ".", " -r", "😍"]
strings.zip(squeeze_these).each do |str, st|
puts "original: «««
st.chars.each do |c|
ssq = str.squeeze(c)
puts "
end
puts
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
|
Change the following Ruby code into VB without altering its purpose. | 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 ",
"😍😀🙌💃😍😍😍🙌",]
squeeze_these = ["", "-", "7", ".", " -r", "😍"]
strings.zip(squeeze_these).each do |str, st|
puts "original: «««
st.chars.each do |c|
ssq = str.squeeze(c)
puts "
end
puts
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
|
Write a version of this Ruby function in Go with identical behavior. | 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 ",
"😍😀🙌💃😍😍😍🙌",]
squeeze_these = ["", "-", "7", ".", " -r", "😍"]
strings.zip(squeeze_these).each do |str, st|
puts "original: «««
st.chars.each do |c|
ssq = str.squeeze(c)
puts "
end
puts
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)
}
}
}
|
Please provide an equivalent version of this Ruby code in Go. | 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 ",
"😍😀🙌💃😍😍😍🙌",]
squeeze_these = ["", "-", "7", ".", " -r", "😍"]
strings.zip(squeeze_these).each do |str, st|
puts "original: «««
st.chars.each do |c|
ssq = str.squeeze(c)
puts "
end
puts
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)
}
}
}
|
Generate a C translation of this Scala snippet without changing its computational steps. | fun main() {
val testStrings = arrayOf(
"",
"\"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")
val testChar = arrayOf(
" ",
"-",
"7",
".",
" -r",
"5",
"e",
"s")
for (testNum in testStrings.indices) {
val s = testStrings[testNum]
for (c in testChar[testNum].toCharArray()) {
val 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 fun squeeze(input: String, include: Char): String {
val sb = StringBuilder()
for (i in input.indices) {
if (i == 0 || input[i - 1] != input[i] || input[i - 1] == input[i] && input[i] != include) {
sb.append(input[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;
}
|
Translate this program into C but keep the logic exactly as in Scala. | fun main() {
val testStrings = arrayOf(
"",
"\"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")
val testChar = arrayOf(
" ",
"-",
"7",
".",
" -r",
"5",
"e",
"s")
for (testNum in testStrings.indices) {
val s = testStrings[testNum]
for (c in testChar[testNum].toCharArray()) {
val 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 fun squeeze(input: String, include: Char): String {
val sb = StringBuilder()
for (i in input.indices) {
if (i == 0 || input[i - 1] != input[i] || input[i - 1] == input[i] && input[i] != include) {
sb.append(input[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;
}
|
Produce a functionally identical C# code for the snippet given in Scala. | fun main() {
val testStrings = arrayOf(
"",
"\"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")
val testChar = arrayOf(
" ",
"-",
"7",
".",
" -r",
"5",
"e",
"s")
for (testNum in testStrings.indices) {
val s = testStrings[testNum]
for (c in testChar[testNum].toCharArray()) {
val 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 fun squeeze(input: String, include: Char): String {
val sb = StringBuilder()
for (i in input.indices) {
if (i == 0 || input[i - 1] != input[i] || input[i - 1] == input[i] && input[i] != include) {
sb.append(input[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());
}
|
Preserve the algorithm and functionality while converting the code from Scala to C#. | fun main() {
val testStrings = arrayOf(
"",
"\"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")
val testChar = arrayOf(
" ",
"-",
"7",
".",
" -r",
"5",
"e",
"s")
for (testNum in testStrings.indices) {
val s = testStrings[testNum]
for (c in testChar[testNum].toCharArray()) {
val 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 fun squeeze(input: String, include: Char): String {
val sb = StringBuilder()
for (i in input.indices) {
if (i == 0 || input[i - 1] != input[i] || input[i - 1] == input[i] && input[i] != include) {
sb.append(input[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());
}
|
Produce a functionally identical C++ code for the snippet given in Scala. | fun main() {
val testStrings = arrayOf(
"",
"\"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")
val testChar = arrayOf(
" ",
"-",
"7",
".",
" -r",
"5",
"e",
"s")
for (testNum in testStrings.indices) {
val s = testStrings[testNum]
for (c in testChar[testNum].toCharArray()) {
val 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 fun squeeze(input: String, include: Char): String {
val sb = StringBuilder()
for (i in input.indices) {
if (i == 0 || input[i - 1] != input[i] || input[i - 1] == input[i] && input[i] != include) {
sb.append(input[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;
}
|
Convert the following code from Scala to C++, ensuring the logic remains intact. | fun main() {
val testStrings = arrayOf(
"",
"\"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")
val testChar = arrayOf(
" ",
"-",
"7",
".",
" -r",
"5",
"e",
"s")
for (testNum in testStrings.indices) {
val s = testStrings[testNum]
for (c in testChar[testNum].toCharArray()) {
val 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 fun squeeze(input: String, include: Char): String {
val sb = StringBuilder()
for (i in input.indices) {
if (i == 0 || input[i - 1] != input[i] || input[i - 1] == input[i] && input[i] != include) {
sb.append(input[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;
}
|
Can you help me rewrite this code in Java instead of Scala, keeping it the same logically? | fun main() {
val testStrings = arrayOf(
"",
"\"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")
val testChar = arrayOf(
" ",
"-",
"7",
".",
" -r",
"5",
"e",
"s")
for (testNum in testStrings.indices) {
val s = testStrings[testNum]
for (c in testChar[testNum].toCharArray()) {
val 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 fun squeeze(input: String, include: Char): String {
val sb = StringBuilder()
for (i in input.indices) {
if (i == 0 || input[i - 1] != input[i] || input[i - 1] == input[i] && input[i] != include) {
sb.append(input[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();
}
}
|
Please provide an equivalent version of this Scala code in Java. | fun main() {
val testStrings = arrayOf(
"",
"\"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")
val testChar = arrayOf(
" ",
"-",
"7",
".",
" -r",
"5",
"e",
"s")
for (testNum in testStrings.indices) {
val s = testStrings[testNum]
for (c in testChar[testNum].toCharArray()) {
val 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 fun squeeze(input: String, include: Char): String {
val sb = StringBuilder()
for (i in input.indices) {
if (i == 0 || input[i - 1] != input[i] || input[i - 1] == input[i] && input[i] != include) {
sb.append(input[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();
}
}
|
Ensure the translated Python code behaves exactly like the original Scala snippet. | fun main() {
val testStrings = arrayOf(
"",
"\"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")
val testChar = arrayOf(
" ",
"-",
"7",
".",
" -r",
"5",
"e",
"s")
for (testNum in testStrings.indices) {
val s = testStrings[testNum]
for (c in testChar[testNum].toCharArray()) {
val 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 fun squeeze(input: String, include: Char): String {
val sb = StringBuilder()
for (i in input.indices) {
if (i == 0 || input[i - 1] != input[i] || input[i - 1] == input[i] && input[i] != include) {
sb.append(input[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}»»»" )
|
Rewrite this program in Python while keeping its functionality equivalent to the Scala version. | fun main() {
val testStrings = arrayOf(
"",
"\"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")
val testChar = arrayOf(
" ",
"-",
"7",
".",
" -r",
"5",
"e",
"s")
for (testNum in testStrings.indices) {
val s = testStrings[testNum]
for (c in testChar[testNum].toCharArray()) {
val 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 fun squeeze(input: String, include: Char): String {
val sb = StringBuilder()
for (i in input.indices) {
if (i == 0 || input[i - 1] != input[i] || input[i - 1] == input[i] && input[i] != include) {
sb.append(input[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}»»»" )
|
Rewrite this program in VB while keeping its functionality equivalent to the Scala version. | fun main() {
val testStrings = arrayOf(
"",
"\"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")
val testChar = arrayOf(
" ",
"-",
"7",
".",
" -r",
"5",
"e",
"s")
for (testNum in testStrings.indices) {
val s = testStrings[testNum]
for (c in testChar[testNum].toCharArray()) {
val 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 fun squeeze(input: String, include: Char): String {
val sb = StringBuilder()
for (i in input.indices) {
if (i == 0 || input[i - 1] != input[i] || input[i - 1] == input[i] && input[i] != include) {
sb.append(input[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
|
Port the provided Scala code into VB while preserving the original functionality. | fun main() {
val testStrings = arrayOf(
"",
"\"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")
val testChar = arrayOf(
" ",
"-",
"7",
".",
" -r",
"5",
"e",
"s")
for (testNum in testStrings.indices) {
val s = testStrings[testNum]
for (c in testChar[testNum].toCharArray()) {
val 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 fun squeeze(input: String, include: Char): String {
val sb = StringBuilder()
for (i in input.indices) {
if (i == 0 || input[i - 1] != input[i] || input[i - 1] == input[i] && input[i] != include) {
sb.append(input[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
|
Write the same code in Go as shown below in Scala. | fun main() {
val testStrings = arrayOf(
"",
"\"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")
val testChar = arrayOf(
" ",
"-",
"7",
".",
" -r",
"5",
"e",
"s")
for (testNum in testStrings.indices) {
val s = testStrings[testNum]
for (c in testChar[testNum].toCharArray()) {
val 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 fun squeeze(input: String, include: Char): String {
val sb = StringBuilder()
for (i in input.indices) {
if (i == 0 || input[i - 1] != input[i] || input[i - 1] == input[i] && input[i] != include) {
sb.append(input[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)
}
}
}
|
Rewrite this program in Go while keeping its functionality equivalent to the Scala version. | fun main() {
val testStrings = arrayOf(
"",
"\"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")
val testChar = arrayOf(
" ",
"-",
"7",
".",
" -r",
"5",
"e",
"s")
for (testNum in testStrings.indices) {
val s = testStrings[testNum]
for (c in testChar[testNum].toCharArray()) {
val 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 fun squeeze(input: String, include: Char): String {
val sb = StringBuilder()
for (i in input.indices) {
if (i == 0 || input[i - 1] != input[i] || input[i - 1] == input[i] && input[i] != include) {
sb.append(input[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 Tcl to C. |
set test {
{} {" "}
{"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 } {" " "-" "r"}
{The better the 4-wheel drive, the further you'll be from help when ya get stuck!} {"e"} ;
{headmistressship} {"s"}
}
foreach {str chrs} $test {
foreach c $chrs {
set c [regsub -all {\W} $c {\\&}]
set re [subst -noback {($c)(\1+)}] ;
set sub [regsub -all $re $str {\1}]
puts [format "Original (length %3d): %s" [string length $str] $str]
puts [format "Subbed (length %3d): %s" [string length $sub] $sub]
puts ----------------------
}
}
| #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;
}
|
Keep all operations the same but rewrite the snippet in C. |
set test {
{} {" "}
{"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 } {" " "-" "r"}
{The better the 4-wheel drive, the further you'll be from help when ya get stuck!} {"e"} ;
{headmistressship} {"s"}
}
foreach {str chrs} $test {
foreach c $chrs {
set c [regsub -all {\W} $c {\\&}]
set re [subst -noback {($c)(\1+)}] ;
set sub [regsub -all $re $str {\1}]
puts [format "Original (length %3d): %s" [string length $str] $str]
puts [format "Subbed (length %3d): %s" [string length $sub] $sub]
puts ----------------------
}
}
| #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;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.