Instruction stringlengths 45 106 | input_code stringlengths 1 13.7k | output_code stringlengths 1 13.7k |
|---|---|---|
Port the following code from AutoHotKey to VB with equivalent syntax and logic. | squeezable_string(str, char){
for i, ch in StrSplit(str){
if (ch <> prev) || !InStr(ch, char)
res .= ch
prev := ch
}
result := "
(ltrim
Original string:`t" StrLen(str) " characters`t«««" str "»»»
Squeezable Character «««" char "»»»
Resultant string:`t" StrLen(res) " characters`t«««" res "»»»
)"
return result
}
| 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 AutoHotKey code snippet into VB without altering its behavior. | squeezable_string(str, char){
for i, ch in StrSplit(str){
if (ch <> prev) || !InStr(ch, char)
res .= ch
prev := ch
}
result := "
(ltrim
Original string:`t" StrLen(str) " characters`t«««" str "»»»
Squeezable Character «««" char "»»»
Resultant string:`t" StrLen(res) " characters`t«««" res "»»»
)"
return result
}
| Imports System.Linq.Enumerable
Module Module1
Function Squeeze(s As String, c As Char) As String
If String.IsNullOrEmpty(s) Then
Return ""
End If
Return s(0) + New String(Range(1, s.Length - 1).Where(Function(i) s(i) <> c OrElse s(i) <> s(i - 1)).Select(Function(i) s(i)).ToArray())
End Function
Sub SqueezeAndPrint(s As String, c As Char)
Console.WriteLine("squeeze:
Console.WriteLine("old: {0} «««{1}»»»", s.Length, s)
s = Squeeze(s, c)
Console.WriteLine("new: {0} «««{1}»»»", s.Length, s)
End Sub
Sub Main()
Const QUOTE = """"
SqueezeAndPrint("", " ")
SqueezeAndPrint(QUOTE & "If I were two-faced, would I be wearing this one?" & QUOTE & " --- Abraham Lincoln ", "-")
SqueezeAndPrint("..1111111111111111111111111111111111111111111111111111111111111117777888", "7")
SqueezeAndPrint("I never give
Dim s = " --- Harry S Truman "
SqueezeAndPrint(s, " ")
SqueezeAndPrint(s, "-")
SqueezeAndPrint(s, "r")
End Sub
End Module
|
Can you help me rewrite this code in Go instead of AutoHotKey, keeping it the same logically? | squeezable_string(str, char){
for i, ch in StrSplit(str){
if (ch <> prev) || !InStr(ch, char)
res .= ch
prev := ch
}
result := "
(ltrim
Original string:`t" StrLen(str) " characters`t«««" str "»»»
Squeezable Character «««" char "»»»
Resultant string:`t" StrLen(res) " characters`t«««" res "»»»
)"
return result
}
| package main
import "fmt"
func squeeze(s string, c rune) (string, int, int) {
r := []rune(s)
le, del := len(r), 0
for i := le - 2; i >= 0; i-- {
if r[i] == c && r[i] == r[i+1] {
copy(r[i:], r[i+1:])
del++
}
}
if del == 0 {
return s, le, le
}
r = r[:le-del]
return string(r), le, len(r)
}
func main() {
strings := []string{
"",
`"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln `,
"..1111111111111111111111111111111111111111111111111111111111111117777888",
"I never give 'em hell, I just tell the truth, and they think it's hell. ",
" --- Harry S Truman ",
"The better the 4-wheel drive, the further you'll be from help when ya get stuck!",
"headmistressship",
"aardvark",
"😍😀🙌💃😍😍😍🙌",
}
chars := [][]rune{{' '}, {'-'}, {'7'}, {'.'}, {' ', '-', 'r'}, {'e'}, {'s'}, {'a'}, {'😍'}}
for i, s := range strings {
for _, c := range chars[i] {
ss, olen, slen := squeeze(s, c)
fmt.Printf("specified character = %q\n", c)
fmt.Printf("original : length = %2d, string = «««%s»»»\n", olen, s)
fmt.Printf("squeezed : length = %2d, string = «««%s»»»\n\n", slen, ss)
}
}
}
|
Port the provided AutoHotKey code into Go while preserving the original functionality. | squeezable_string(str, char){
for i, ch in StrSplit(str){
if (ch <> prev) || !InStr(ch, char)
res .= ch
prev := ch
}
result := "
(ltrim
Original string:`t" StrLen(str) " characters`t«««" str "»»»
Squeezable Character «««" char "»»»
Resultant string:`t" StrLen(res) " characters`t«««" res "»»»
)"
return result
}
| package main
import "fmt"
func squeeze(s string, c rune) (string, int, int) {
r := []rune(s)
le, del := len(r), 0
for i := le - 2; i >= 0; i-- {
if r[i] == c && r[i] == r[i+1] {
copy(r[i:], r[i+1:])
del++
}
}
if del == 0 {
return s, le, le
}
r = r[:le-del]
return string(r), le, len(r)
}
func main() {
strings := []string{
"",
`"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln `,
"..1111111111111111111111111111111111111111111111111111111111111117777888",
"I never give 'em hell, I just tell the truth, and they think it's hell. ",
" --- Harry S Truman ",
"The better the 4-wheel drive, the further you'll be from help when ya get stuck!",
"headmistressship",
"aardvark",
"😍😀🙌💃😍😍😍🙌",
}
chars := [][]rune{{' '}, {'-'}, {'7'}, {'.'}, {' ', '-', 'r'}, {'e'}, {'s'}, {'a'}, {'😍'}}
for i, s := range strings {
for _, c := range chars[i] {
ss, olen, slen := squeeze(s, c)
fmt.Printf("specified character = %q\n", c)
fmt.Printf("original : length = %2d, string = «««%s»»»\n", olen, s)
fmt.Printf("squeezed : length = %2d, string = «««%s»»»\n\n", slen, ss)
}
}
}
|
Convert this AWK block to C, preserving its control flow and logic. |
BEGIN {
arr[++n] = "" ; arr2[n] = " "
arr[++n] = "\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln " ; arr2[n] = "-"
arr[++n] = "..1111111111111111111111111111111111111111111111111111111111111117777888" ; arr2[n] = "7"
arr[++n] = "I never give 'em hell, I just tell the truth, and they think it's hell. " ; arr2[n] = "."
arr[++n] = " --- Harry S Truman " ; arr2[n] = " -r"
arr[++n] = "The better the 4-wheel drive, the further you'll be from help when ya get stuck!" ; arr2[n] = "e"
arr[++n] = "headmistressship" ; arr2[n] = "s"
for (i=1; i<=n; i++) {
for (j=1; j<=length(arr2[i]); j++) {
main(arr[i],substr(arr2[i],j,1))
}
}
exit(0)
}
function main(str,chr, c,i,new_str,prev_c) {
for (i=1; i<=length(str); i++) {
c = substr(str,i,1)
if (!(prev_c == c && c == chr)) {
prev_c = c
new_str = new_str c
}
}
printf("use: '%s'\n",chr)
printf("old: %2d <<<%s>>>\n",length(str),str)
printf("new: %2d <<<%s>>>\n\n",length(new_str),new_str)
}
| #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 AWK code into C while preserving the original functionality. |
BEGIN {
arr[++n] = "" ; arr2[n] = " "
arr[++n] = "\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln " ; arr2[n] = "-"
arr[++n] = "..1111111111111111111111111111111111111111111111111111111111111117777888" ; arr2[n] = "7"
arr[++n] = "I never give 'em hell, I just tell the truth, and they think it's hell. " ; arr2[n] = "."
arr[++n] = " --- Harry S Truman " ; arr2[n] = " -r"
arr[++n] = "The better the 4-wheel drive, the further you'll be from help when ya get stuck!" ; arr2[n] = "e"
arr[++n] = "headmistressship" ; arr2[n] = "s"
for (i=1; i<=n; i++) {
for (j=1; j<=length(arr2[i]); j++) {
main(arr[i],substr(arr2[i],j,1))
}
}
exit(0)
}
function main(str,chr, c,i,new_str,prev_c) {
for (i=1; i<=length(str); i++) {
c = substr(str,i,1)
if (!(prev_c == c && c == chr)) {
prev_c = c
new_str = new_str c
}
}
printf("use: '%s'\n",chr)
printf("old: %2d <<<%s>>>\n",length(str),str)
printf("new: %2d <<<%s>>>\n\n",length(new_str),new_str)
}
| #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 AWK version. |
BEGIN {
arr[++n] = "" ; arr2[n] = " "
arr[++n] = "\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln " ; arr2[n] = "-"
arr[++n] = "..1111111111111111111111111111111111111111111111111111111111111117777888" ; arr2[n] = "7"
arr[++n] = "I never give 'em hell, I just tell the truth, and they think it's hell. " ; arr2[n] = "."
arr[++n] = " --- Harry S Truman " ; arr2[n] = " -r"
arr[++n] = "The better the 4-wheel drive, the further you'll be from help when ya get stuck!" ; arr2[n] = "e"
arr[++n] = "headmistressship" ; arr2[n] = "s"
for (i=1; i<=n; i++) {
for (j=1; j<=length(arr2[i]); j++) {
main(arr[i],substr(arr2[i],j,1))
}
}
exit(0)
}
function main(str,chr, c,i,new_str,prev_c) {
for (i=1; i<=length(str); i++) {
c = substr(str,i,1)
if (!(prev_c == c && c == chr)) {
prev_c = c
new_str = new_str c
}
}
printf("use: '%s'\n",chr)
printf("old: %2d <<<%s>>>\n",length(str),str)
printf("new: %2d <<<%s>>>\n\n",length(new_str),new_str)
}
| 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 AWK version. |
BEGIN {
arr[++n] = "" ; arr2[n] = " "
arr[++n] = "\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln " ; arr2[n] = "-"
arr[++n] = "..1111111111111111111111111111111111111111111111111111111111111117777888" ; arr2[n] = "7"
arr[++n] = "I never give 'em hell, I just tell the truth, and they think it's hell. " ; arr2[n] = "."
arr[++n] = " --- Harry S Truman " ; arr2[n] = " -r"
arr[++n] = "The better the 4-wheel drive, the further you'll be from help when ya get stuck!" ; arr2[n] = "e"
arr[++n] = "headmistressship" ; arr2[n] = "s"
for (i=1; i<=n; i++) {
for (j=1; j<=length(arr2[i]); j++) {
main(arr[i],substr(arr2[i],j,1))
}
}
exit(0)
}
function main(str,chr, c,i,new_str,prev_c) {
for (i=1; i<=length(str); i++) {
c = substr(str,i,1)
if (!(prev_c == c && c == chr)) {
prev_c = c
new_str = new_str c
}
}
printf("use: '%s'\n",chr)
printf("old: %2d <<<%s>>>\n",length(str),str)
printf("new: %2d <<<%s>>>\n\n",length(new_str),new_str)
}
| 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++. |
BEGIN {
arr[++n] = "" ; arr2[n] = " "
arr[++n] = "\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln " ; arr2[n] = "-"
arr[++n] = "..1111111111111111111111111111111111111111111111111111111111111117777888" ; arr2[n] = "7"
arr[++n] = "I never give 'em hell, I just tell the truth, and they think it's hell. " ; arr2[n] = "."
arr[++n] = " --- Harry S Truman " ; arr2[n] = " -r"
arr[++n] = "The better the 4-wheel drive, the further you'll be from help when ya get stuck!" ; arr2[n] = "e"
arr[++n] = "headmistressship" ; arr2[n] = "s"
for (i=1; i<=n; i++) {
for (j=1; j<=length(arr2[i]); j++) {
main(arr[i],substr(arr2[i],j,1))
}
}
exit(0)
}
function main(str,chr, c,i,new_str,prev_c) {
for (i=1; i<=length(str); i++) {
c = substr(str,i,1)
if (!(prev_c == c && c == chr)) {
prev_c = c
new_str = new_str c
}
}
printf("use: '%s'\n",chr)
printf("old: %2d <<<%s>>>\n",length(str),str)
printf("new: %2d <<<%s>>>\n\n",length(new_str),new_str)
}
| #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 AWK snippet to C++ and keep its semantics consistent. |
BEGIN {
arr[++n] = "" ; arr2[n] = " "
arr[++n] = "\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln " ; arr2[n] = "-"
arr[++n] = "..1111111111111111111111111111111111111111111111111111111111111117777888" ; arr2[n] = "7"
arr[++n] = "I never give 'em hell, I just tell the truth, and they think it's hell. " ; arr2[n] = "."
arr[++n] = " --- Harry S Truman " ; arr2[n] = " -r"
arr[++n] = "The better the 4-wheel drive, the further you'll be from help when ya get stuck!" ; arr2[n] = "e"
arr[++n] = "headmistressship" ; arr2[n] = "s"
for (i=1; i<=n; i++) {
for (j=1; j<=length(arr2[i]); j++) {
main(arr[i],substr(arr2[i],j,1))
}
}
exit(0)
}
function main(str,chr, c,i,new_str,prev_c) {
for (i=1; i<=length(str); i++) {
c = substr(str,i,1)
if (!(prev_c == c && c == chr)) {
prev_c = c
new_str = new_str c
}
}
printf("use: '%s'\n",chr)
printf("old: %2d <<<%s>>>\n",length(str),str)
printf("new: %2d <<<%s>>>\n\n",length(new_str),new_str)
}
| #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 AWK to Java, ensuring the logic remains intact. |
BEGIN {
arr[++n] = "" ; arr2[n] = " "
arr[++n] = "\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln " ; arr2[n] = "-"
arr[++n] = "..1111111111111111111111111111111111111111111111111111111111111117777888" ; arr2[n] = "7"
arr[++n] = "I never give 'em hell, I just tell the truth, and they think it's hell. " ; arr2[n] = "."
arr[++n] = " --- Harry S Truman " ; arr2[n] = " -r"
arr[++n] = "The better the 4-wheel drive, the further you'll be from help when ya get stuck!" ; arr2[n] = "e"
arr[++n] = "headmistressship" ; arr2[n] = "s"
for (i=1; i<=n; i++) {
for (j=1; j<=length(arr2[i]); j++) {
main(arr[i],substr(arr2[i],j,1))
}
}
exit(0)
}
function main(str,chr, c,i,new_str,prev_c) {
for (i=1; i<=length(str); i++) {
c = substr(str,i,1)
if (!(prev_c == c && c == chr)) {
prev_c = c
new_str = new_str c
}
}
printf("use: '%s'\n",chr)
printf("old: %2d <<<%s>>>\n",length(str),str)
printf("new: %2d <<<%s>>>\n\n",length(new_str),new_str)
}
|
public class StringSqueezable {
public static void main(String[] args) {
String[] testStrings = new String[] {
"",
"\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln ",
"..1111111111111111111111111111111111111111111111111111111111111117777888",
"I never give 'em hell, I just tell the truth, and they think it's hell. ",
" --- Harry S Truman ",
"122333444455555666666777777788888888999999999",
"The better the 4-wheel drive, the further you'll be from help when ya get stuck!",
"headmistressship"};
String[] testChar = new String[] {
" ",
"-",
"7",
".",
" -r",
"5",
"e",
"s"};
for ( int testNum = 0 ; testNum < testStrings.length ; testNum++ ) {
String s = testStrings[testNum];
for ( char c : testChar[testNum].toCharArray() ) {
String result = squeeze(s, c);
System.out.printf("use: '%c'%nold: %2d <<<%s>>>%nnew: %2d <<<%s>>>%n%n", c, s.length(), s, result.length(), result);
}
}
}
private static String squeeze(String in, char include) {
StringBuilder sb = new StringBuilder();
for ( int i = 0 ; i < in.length() ; i++ ) {
if ( i == 0 || in.charAt(i-1) != in.charAt(i) || (in.charAt(i-1) == in.charAt(i) && in.charAt(i) != include)) {
sb.append(in.charAt(i));
}
}
return sb.toString();
}
}
|
Rewrite this program in Java while keeping its functionality equivalent to the AWK version. |
BEGIN {
arr[++n] = "" ; arr2[n] = " "
arr[++n] = "\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln " ; arr2[n] = "-"
arr[++n] = "..1111111111111111111111111111111111111111111111111111111111111117777888" ; arr2[n] = "7"
arr[++n] = "I never give 'em hell, I just tell the truth, and they think it's hell. " ; arr2[n] = "."
arr[++n] = " --- Harry S Truman " ; arr2[n] = " -r"
arr[++n] = "The better the 4-wheel drive, the further you'll be from help when ya get stuck!" ; arr2[n] = "e"
arr[++n] = "headmistressship" ; arr2[n] = "s"
for (i=1; i<=n; i++) {
for (j=1; j<=length(arr2[i]); j++) {
main(arr[i],substr(arr2[i],j,1))
}
}
exit(0)
}
function main(str,chr, c,i,new_str,prev_c) {
for (i=1; i<=length(str); i++) {
c = substr(str,i,1)
if (!(prev_c == c && c == chr)) {
prev_c = c
new_str = new_str c
}
}
printf("use: '%s'\n",chr)
printf("old: %2d <<<%s>>>\n",length(str),str)
printf("new: %2d <<<%s>>>\n\n",length(new_str),new_str)
}
|
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 a Python translation of this AWK snippet without changing its computational steps. |
BEGIN {
arr[++n] = "" ; arr2[n] = " "
arr[++n] = "\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln " ; arr2[n] = "-"
arr[++n] = "..1111111111111111111111111111111111111111111111111111111111111117777888" ; arr2[n] = "7"
arr[++n] = "I never give 'em hell, I just tell the truth, and they think it's hell. " ; arr2[n] = "."
arr[++n] = " --- Harry S Truman " ; arr2[n] = " -r"
arr[++n] = "The better the 4-wheel drive, the further you'll be from help when ya get stuck!" ; arr2[n] = "e"
arr[++n] = "headmistressship" ; arr2[n] = "s"
for (i=1; i<=n; i++) {
for (j=1; j<=length(arr2[i]); j++) {
main(arr[i],substr(arr2[i],j,1))
}
}
exit(0)
}
function main(str,chr, c,i,new_str,prev_c) {
for (i=1; i<=length(str); i++) {
c = substr(str,i,1)
if (!(prev_c == c && c == chr)) {
prev_c = c
new_str = new_str c
}
}
printf("use: '%s'\n",chr)
printf("old: %2d <<<%s>>>\n",length(str),str)
printf("new: %2d <<<%s>>>\n\n",length(new_str),new_str)
}
| 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 AWK snippet to Python and keep its semantics consistent. |
BEGIN {
arr[++n] = "" ; arr2[n] = " "
arr[++n] = "\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln " ; arr2[n] = "-"
arr[++n] = "..1111111111111111111111111111111111111111111111111111111111111117777888" ; arr2[n] = "7"
arr[++n] = "I never give 'em hell, I just tell the truth, and they think it's hell. " ; arr2[n] = "."
arr[++n] = " --- Harry S Truman " ; arr2[n] = " -r"
arr[++n] = "The better the 4-wheel drive, the further you'll be from help when ya get stuck!" ; arr2[n] = "e"
arr[++n] = "headmistressship" ; arr2[n] = "s"
for (i=1; i<=n; i++) {
for (j=1; j<=length(arr2[i]); j++) {
main(arr[i],substr(arr2[i],j,1))
}
}
exit(0)
}
function main(str,chr, c,i,new_str,prev_c) {
for (i=1; i<=length(str); i++) {
c = substr(str,i,1)
if (!(prev_c == c && c == chr)) {
prev_c = c
new_str = new_str c
}
}
printf("use: '%s'\n",chr)
printf("old: %2d <<<%s>>>\n",length(str),str)
printf("new: %2d <<<%s>>>\n\n",length(new_str),new_str)
}
| 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 following code from AWK to VB with equivalent syntax and logic. |
BEGIN {
arr[++n] = "" ; arr2[n] = " "
arr[++n] = "\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln " ; arr2[n] = "-"
arr[++n] = "..1111111111111111111111111111111111111111111111111111111111111117777888" ; arr2[n] = "7"
arr[++n] = "I never give 'em hell, I just tell the truth, and they think it's hell. " ; arr2[n] = "."
arr[++n] = " --- Harry S Truman " ; arr2[n] = " -r"
arr[++n] = "The better the 4-wheel drive, the further you'll be from help when ya get stuck!" ; arr2[n] = "e"
arr[++n] = "headmistressship" ; arr2[n] = "s"
for (i=1; i<=n; i++) {
for (j=1; j<=length(arr2[i]); j++) {
main(arr[i],substr(arr2[i],j,1))
}
}
exit(0)
}
function main(str,chr, c,i,new_str,prev_c) {
for (i=1; i<=length(str); i++) {
c = substr(str,i,1)
if (!(prev_c == c && c == chr)) {
prev_c = c
new_str = new_str c
}
}
printf("use: '%s'\n",chr)
printf("old: %2d <<<%s>>>\n",length(str),str)
printf("new: %2d <<<%s>>>\n\n",length(new_str),new_str)
}
| 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 AWK code into VB while preserving the original functionality. |
BEGIN {
arr[++n] = "" ; arr2[n] = " "
arr[++n] = "\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln " ; arr2[n] = "-"
arr[++n] = "..1111111111111111111111111111111111111111111111111111111111111117777888" ; arr2[n] = "7"
arr[++n] = "I never give 'em hell, I just tell the truth, and they think it's hell. " ; arr2[n] = "."
arr[++n] = " --- Harry S Truman " ; arr2[n] = " -r"
arr[++n] = "The better the 4-wheel drive, the further you'll be from help when ya get stuck!" ; arr2[n] = "e"
arr[++n] = "headmistressship" ; arr2[n] = "s"
for (i=1; i<=n; i++) {
for (j=1; j<=length(arr2[i]); j++) {
main(arr[i],substr(arr2[i],j,1))
}
}
exit(0)
}
function main(str,chr, c,i,new_str,prev_c) {
for (i=1; i<=length(str); i++) {
c = substr(str,i,1)
if (!(prev_c == c && c == chr)) {
prev_c = c
new_str = new_str c
}
}
printf("use: '%s'\n",chr)
printf("old: %2d <<<%s>>>\n",length(str),str)
printf("new: %2d <<<%s>>>\n\n",length(new_str),new_str)
}
| Imports System.Linq.Enumerable
Module Module1
Function Squeeze(s As String, c As Char) As String
If String.IsNullOrEmpty(s) Then
Return ""
End If
Return s(0) + New String(Range(1, s.Length - 1).Where(Function(i) s(i) <> c OrElse s(i) <> s(i - 1)).Select(Function(i) s(i)).ToArray())
End Function
Sub SqueezeAndPrint(s As String, c As Char)
Console.WriteLine("squeeze:
Console.WriteLine("old: {0} «««{1}»»»", s.Length, s)
s = Squeeze(s, c)
Console.WriteLine("new: {0} «««{1}»»»", s.Length, s)
End Sub
Sub Main()
Const QUOTE = """"
SqueezeAndPrint("", " ")
SqueezeAndPrint(QUOTE & "If I were two-faced, would I be wearing this one?" & QUOTE & " --- Abraham Lincoln ", "-")
SqueezeAndPrint("..1111111111111111111111111111111111111111111111111111111111111117777888", "7")
SqueezeAndPrint("I never give
Dim s = " --- Harry S Truman "
SqueezeAndPrint(s, " ")
SqueezeAndPrint(s, "-")
SqueezeAndPrint(s, "r")
End Sub
End Module
|
Produce a functionally identical Go code for the snippet given in AWK. |
BEGIN {
arr[++n] = "" ; arr2[n] = " "
arr[++n] = "\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln " ; arr2[n] = "-"
arr[++n] = "..1111111111111111111111111111111111111111111111111111111111111117777888" ; arr2[n] = "7"
arr[++n] = "I never give 'em hell, I just tell the truth, and they think it's hell. " ; arr2[n] = "."
arr[++n] = " --- Harry S Truman " ; arr2[n] = " -r"
arr[++n] = "The better the 4-wheel drive, the further you'll be from help when ya get stuck!" ; arr2[n] = "e"
arr[++n] = "headmistressship" ; arr2[n] = "s"
for (i=1; i<=n; i++) {
for (j=1; j<=length(arr2[i]); j++) {
main(arr[i],substr(arr2[i],j,1))
}
}
exit(0)
}
function main(str,chr, c,i,new_str,prev_c) {
for (i=1; i<=length(str); i++) {
c = substr(str,i,1)
if (!(prev_c == c && c == chr)) {
prev_c = c
new_str = new_str c
}
}
printf("use: '%s'\n",chr)
printf("old: %2d <<<%s>>>\n",length(str),str)
printf("new: %2d <<<%s>>>\n\n",length(new_str),new_str)
}
| 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 AWK version. |
BEGIN {
arr[++n] = "" ; arr2[n] = " "
arr[++n] = "\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln " ; arr2[n] = "-"
arr[++n] = "..1111111111111111111111111111111111111111111111111111111111111117777888" ; arr2[n] = "7"
arr[++n] = "I never give 'em hell, I just tell the truth, and they think it's hell. " ; arr2[n] = "."
arr[++n] = " --- Harry S Truman " ; arr2[n] = " -r"
arr[++n] = "The better the 4-wheel drive, the further you'll be from help when ya get stuck!" ; arr2[n] = "e"
arr[++n] = "headmistressship" ; arr2[n] = "s"
for (i=1; i<=n; i++) {
for (j=1; j<=length(arr2[i]); j++) {
main(arr[i],substr(arr2[i],j,1))
}
}
exit(0)
}
function main(str,chr, c,i,new_str,prev_c) {
for (i=1; i<=length(str); i++) {
c = substr(str,i,1)
if (!(prev_c == c && c == chr)) {
prev_c = c
new_str = new_str c
}
}
printf("use: '%s'\n",chr)
printf("old: %2d <<<%s>>>\n",length(str),str)
printf("new: %2d <<<%s>>>\n\n",length(new_str),new_str)
}
| package main
import "fmt"
func squeeze(s string, c rune) (string, int, int) {
r := []rune(s)
le, del := len(r), 0
for i := le - 2; i >= 0; i-- {
if r[i] == c && r[i] == r[i+1] {
copy(r[i:], r[i+1:])
del++
}
}
if del == 0 {
return s, le, le
}
r = r[:le-del]
return string(r), le, len(r)
}
func main() {
strings := []string{
"",
`"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln `,
"..1111111111111111111111111111111111111111111111111111111111111117777888",
"I never give 'em hell, I just tell the truth, and they think it's hell. ",
" --- Harry S Truman ",
"The better the 4-wheel drive, the further you'll be from help when ya get stuck!",
"headmistressship",
"aardvark",
"😍😀🙌💃😍😍😍🙌",
}
chars := [][]rune{{' '}, {'-'}, {'7'}, {'.'}, {' ', '-', 'r'}, {'e'}, {'s'}, {'a'}, {'😍'}}
for i, s := range strings {
for _, c := range chars[i] {
ss, olen, slen := squeeze(s, c)
fmt.Printf("specified character = %q\n", c)
fmt.Printf("original : length = %2d, string = «««%s»»»\n", olen, s)
fmt.Printf("squeezed : length = %2d, string = «««%s»»»\n\n", slen, ss)
}
}
}
|
Write the same code in C as shown below in Clojure. | (defn squeeze [s c]
(let [spans (partition-by #(= c %) s)
span-out (fn [span]
(if (= c (first span))
(str c)
(apply str span)))]
(apply str (map span-out spans))))
(defn test-squeeze [s c]
(let [out (squeeze s c)]
(println (format "Input: <<<%s>>> (len %d)\n" s (count s))
(format "becomes: <<<%s>>> (len %d)" out (count out)))))
| #include<string.h>
#include<stdlib.h>
#include<stdio.h>
#define COLLAPSE 0
#define SQUEEZE 1
typedef struct charList{
char c;
struct charList *next;
} charList;
int strcmpi(char str1[100],char str2[100]){
int len1 = strlen(str1), len2 = strlen(str2), i;
if(len1!=len2){
return 1;
}
else{
for(i=0;i<len1;i++){
if((str1[i]>='A'&&str1[i]<='Z')&&(str2[i]>='a'&&str2[i]<='z')&&(str2[i]-65!=str1[i]))
return 1;
else if((str2[i]>='A'&&str2[i]<='Z')&&(str1[i]>='a'&&str1[i]<='z')&&(str1[i]-65!=str2[i]))
return 1;
else if(str1[i]!=str2[i])
return 1;
}
}
return 0;
}
charList *strToCharList(char* str){
int len = strlen(str),i;
charList *list, *iterator, *nextChar;
list = (charList*)malloc(sizeof(charList));
list->c = str[0];
list->next = NULL;
iterator = list;
for(i=1;i<len;i++){
nextChar = (charList*)malloc(sizeof(charList));
nextChar->c = str[i];
nextChar->next = NULL;
iterator->next = nextChar;
iterator = nextChar;
}
return list;
}
char* charListToString(charList* list){
charList* iterator = list;
int count = 0,i;
char* str;
while(iterator!=NULL){
count++;
iterator = iterator->next;
}
str = (char*)malloc((count+1)*sizeof(char));
iterator = list;
for(i=0;i<count;i++){
str[i] = iterator->c;
iterator = iterator->next;
}
free(list);
str[i] = '\0';
return str;
}
char* processString(char str[100],int operation, char squeezeChar){
charList *strList = strToCharList(str),*iterator = strList, *scout;
if(operation==SQUEEZE){
while(iterator!=NULL){
if(iterator->c==squeezeChar){
scout = iterator->next;
while(scout!=NULL && scout->c==squeezeChar){
iterator->next = scout->next;
scout->next = NULL;
free(scout);
scout = iterator->next;
}
}
iterator = iterator->next;
}
}
else{
while(iterator!=NULL && iterator->next!=NULL){
if(iterator->c == (iterator->next)->c){
scout = iterator->next;
squeezeChar = iterator->c;
while(scout!=NULL && scout->c==squeezeChar){
iterator->next = scout->next;
scout->next = NULL;
free(scout);
scout = iterator->next;
}
}
iterator = iterator->next;
}
}
return charListToString(strList);
}
void printResults(char originalString[100], char finalString[100], int operation, char squeezeChar){
if(operation==SQUEEZE){
printf("Specified Operation : SQUEEZE\nTarget Character : %c",squeezeChar);
}
else
printf("Specified Operation : COLLAPSE");
printf("\nOriginal %c%c%c%s%c%c%c\nLength : %d",174,174,174,originalString,175,175,175,(int)strlen(originalString));
printf("\nFinal %c%c%c%s%c%c%c\nLength : %d\n",174,174,174,finalString,175,175,175,(int)strlen(finalString));
}
int main(int argc, char** argv){
int operation;
char squeezeChar;
if(argc<3||argc>4){
printf("Usage : %s <SQUEEZE|COLLAPSE> <String to be processed> <Character to be squeezed, if operation is SQUEEZE>\n",argv[0]);
return 0;
}
if(strcmpi(argv[1],"SQUEEZE")==0 && argc!=4){
scanf("Please enter characted to be squeezed : %c",&squeezeChar);
operation = SQUEEZE;
}
else if(argc==4){
operation = SQUEEZE;
squeezeChar = argv[3][0];
}
else if(strcmpi(argv[1],"COLLAPSE")==0){
operation = COLLAPSE;
}
if(strlen(argv[2])<2){
printResults(argv[2],argv[2],operation,squeezeChar);
}
else{
printResults(argv[2],processString(argv[2],operation,squeezeChar),operation,squeezeChar);
}
return 0;
}
|
Rewrite the snippet below in C so it works the same as the original Clojure code. | (defn squeeze [s c]
(let [spans (partition-by #(= c %) s)
span-out (fn [span]
(if (= c (first span))
(str c)
(apply str span)))]
(apply str (map span-out spans))))
(defn test-squeeze [s c]
(let [out (squeeze s c)]
(println (format "Input: <<<%s>>> (len %d)\n" s (count s))
(format "becomes: <<<%s>>> (len %d)" out (count out)))))
| #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 Clojure code into C# while preserving the original functionality. | (defn squeeze [s c]
(let [spans (partition-by #(= c %) s)
span-out (fn [span]
(if (= c (first span))
(str c)
(apply str span)))]
(apply str (map span-out spans))))
(defn test-squeeze [s c]
(let [out (squeeze s c)]
(println (format "Input: <<<%s>>> (len %d)\n" s (count s))
(format "becomes: <<<%s>>> (len %d)" out (count out)))))
| using System;
using static System.Linq.Enumerable;
public class Program
{
static void Main()
{
SqueezeAndPrint("", ' ');
SqueezeAndPrint("\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln ", '-');
SqueezeAndPrint("..1111111111111111111111111111111111111111111111111111111111111117777888", '7');
SqueezeAndPrint("I never give 'em hell, I just tell the truth, and they think it's hell. ", '.');
string s = " --- Harry S Truman ";
SqueezeAndPrint(s, ' ');
SqueezeAndPrint(s, '-');
SqueezeAndPrint(s, 'r');
}
static void SqueezeAndPrint(string s, char c) {
Console.WriteLine($"squeeze: '{c}'");
Console.WriteLine($"old: {s.Length} «««{s}»»»");
s = Squeeze(s, c);
Console.WriteLine($"new: {s.Length} «««{s}»»»");
}
static string Squeeze(string s, char c) => string.IsNullOrEmpty(s) ? "" :
s[0] + new string(Range(1, s.Length - 1).Where(i => s[i] != c || s[i] != s[i - 1]).Select(i => s[i]).ToArray());
}
|
Maintain the same structure and functionality when rewriting this code in C#. | (defn squeeze [s c]
(let [spans (partition-by #(= c %) s)
span-out (fn [span]
(if (= c (first span))
(str c)
(apply str span)))]
(apply str (map span-out spans))))
(defn test-squeeze [s c]
(let [out (squeeze s c)]
(println (format "Input: <<<%s>>> (len %d)\n" s (count s))
(format "becomes: <<<%s>>> (len %d)" out (count out)))))
| using System;
using static System.Linq.Enumerable;
public class Program
{
static void Main()
{
SqueezeAndPrint("", ' ');
SqueezeAndPrint("\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln ", '-');
SqueezeAndPrint("..1111111111111111111111111111111111111111111111111111111111111117777888", '7');
SqueezeAndPrint("I never give 'em hell, I just tell the truth, and they think it's hell. ", '.');
string s = " --- Harry S Truman ";
SqueezeAndPrint(s, ' ');
SqueezeAndPrint(s, '-');
SqueezeAndPrint(s, 'r');
}
static void SqueezeAndPrint(string s, char c) {
Console.WriteLine($"squeeze: '{c}'");
Console.WriteLine($"old: {s.Length} «««{s}»»»");
s = Squeeze(s, c);
Console.WriteLine($"new: {s.Length} «««{s}»»»");
}
static string Squeeze(string s, char c) => string.IsNullOrEmpty(s) ? "" :
s[0] + new string(Range(1, s.Length - 1).Where(i => s[i] != c || s[i] != s[i - 1]).Select(i => s[i]).ToArray());
}
|
Convert the following code from Clojure to C++, ensuring the logic remains intact. | (defn squeeze [s c]
(let [spans (partition-by #(= c %) s)
span-out (fn [span]
(if (= c (first span))
(str c)
(apply str span)))]
(apply str (map span-out spans))))
(defn test-squeeze [s c]
(let [out (squeeze s c)]
(println (format "Input: <<<%s>>> (len %d)\n" s (count s))
(format "becomes: <<<%s>>> (len %d)" out (count out)))))
| #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++. | (defn squeeze [s c]
(let [spans (partition-by #(= c %) s)
span-out (fn [span]
(if (= c (first span))
(str c)
(apply str span)))]
(apply str (map span-out spans))))
(defn test-squeeze [s c]
(let [out (squeeze s c)]
(println (format "Input: <<<%s>>> (len %d)\n" s (count s))
(format "becomes: <<<%s>>> (len %d)" out (count out)))))
| #include <algorithm>
#include <string>
#include <iostream>
template<typename char_type>
std::basic_string<char_type> squeeze(std::basic_string<char_type> str, char_type ch) {
auto i = std::unique(str.begin(), str.end(),
[ch](char_type a, char_type b) { return a == ch && b == ch; });
str.erase(i, str.end());
return str;
}
void test(const std::string& str, char ch) {
std::cout << "character: '" << ch << "'\n";
std::cout << "original: <<<" << str << ">>>, length: " << str.length() << '\n';
std::string squeezed(squeeze(str, ch));
std::cout << "result: <<<" << squeezed << ">>>, length: " << squeezed.length() << '\n';
std::cout << '\n';
}
int main(int argc, char** argv) {
test("", ' ');
test("\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln ", '-');
test("..1111111111111111111111111111111111111111111111111111111111111117777888", '7');
test("I never give 'em hell, I just tell the truth, and they think it's hell. ", '.');
std::string truman(" --- Harry S Truman ");
test(truman, ' ');
test(truman, '-');
test(truman, 'r');
return 0;
}
|
Maintain the same structure and functionality when rewriting this code in Java. | (defn squeeze [s c]
(let [spans (partition-by #(= c %) s)
span-out (fn [span]
(if (= c (first span))
(str c)
(apply str span)))]
(apply str (map span-out spans))))
(defn test-squeeze [s c]
(let [out (squeeze s c)]
(println (format "Input: <<<%s>>> (len %d)\n" s (count s))
(format "becomes: <<<%s>>> (len %d)" out (count out)))))
|
public class StringSqueezable {
public static void main(String[] args) {
String[] testStrings = new String[] {
"",
"\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln ",
"..1111111111111111111111111111111111111111111111111111111111111117777888",
"I never give 'em hell, I just tell the truth, and they think it's hell. ",
" --- Harry S Truman ",
"122333444455555666666777777788888888999999999",
"The better the 4-wheel drive, the further you'll be from help when ya get stuck!",
"headmistressship"};
String[] testChar = new String[] {
" ",
"-",
"7",
".",
" -r",
"5",
"e",
"s"};
for ( int testNum = 0 ; testNum < testStrings.length ; testNum++ ) {
String s = testStrings[testNum];
for ( char c : testChar[testNum].toCharArray() ) {
String result = squeeze(s, c);
System.out.printf("use: '%c'%nold: %2d <<<%s>>>%nnew: %2d <<<%s>>>%n%n", c, s.length(), s, result.length(), result);
}
}
}
private static String squeeze(String in, char include) {
StringBuilder sb = new StringBuilder();
for ( int i = 0 ; i < in.length() ; i++ ) {
if ( i == 0 || in.charAt(i-1) != in.charAt(i) || (in.charAt(i-1) == in.charAt(i) && in.charAt(i) != include)) {
sb.append(in.charAt(i));
}
}
return sb.toString();
}
}
|
Write the same algorithm in Java as shown in this Clojure implementation. | (defn squeeze [s c]
(let [spans (partition-by #(= c %) s)
span-out (fn [span]
(if (= c (first span))
(str c)
(apply str span)))]
(apply str (map span-out spans))))
(defn test-squeeze [s c]
(let [out (squeeze s c)]
(println (format "Input: <<<%s>>> (len %d)\n" s (count s))
(format "becomes: <<<%s>>> (len %d)" out (count out)))))
|
public class StringSqueezable {
public static void main(String[] args) {
String[] testStrings = new String[] {
"",
"\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln ",
"..1111111111111111111111111111111111111111111111111111111111111117777888",
"I never give 'em hell, I just tell the truth, and they think it's hell. ",
" --- Harry S Truman ",
"122333444455555666666777777788888888999999999",
"The better the 4-wheel drive, the further you'll be from help when ya get stuck!",
"headmistressship"};
String[] testChar = new String[] {
" ",
"-",
"7",
".",
" -r",
"5",
"e",
"s"};
for ( int testNum = 0 ; testNum < testStrings.length ; testNum++ ) {
String s = testStrings[testNum];
for ( char c : testChar[testNum].toCharArray() ) {
String result = squeeze(s, c);
System.out.printf("use: '%c'%nold: %2d <<<%s>>>%nnew: %2d <<<%s>>>%n%n", c, s.length(), s, result.length(), result);
}
}
}
private static String squeeze(String in, char include) {
StringBuilder sb = new StringBuilder();
for ( int i = 0 ; i < in.length() ; i++ ) {
if ( i == 0 || in.charAt(i-1) != in.charAt(i) || (in.charAt(i-1) == in.charAt(i) && in.charAt(i) != include)) {
sb.append(in.charAt(i));
}
}
return sb.toString();
}
}
|
Rewrite the snippet below in Python so it works the same as the original Clojure code. | (defn squeeze [s c]
(let [spans (partition-by #(= c %) s)
span-out (fn [span]
(if (= c (first span))
(str c)
(apply str span)))]
(apply str (map span-out spans))))
(defn test-squeeze [s c]
(let [out (squeeze s c)]
(println (format "Input: <<<%s>>> (len %d)\n" s (count s))
(format "becomes: <<<%s>>> (len %d)" out (count out)))))
| 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 Clojure. | (defn squeeze [s c]
(let [spans (partition-by #(= c %) s)
span-out (fn [span]
(if (= c (first span))
(str c)
(apply str span)))]
(apply str (map span-out spans))))
(defn test-squeeze [s c]
(let [out (squeeze s c)]
(println (format "Input: <<<%s>>> (len %d)\n" s (count s))
(format "becomes: <<<%s>>> (len %d)" out (count out)))))
| 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 following code from Clojure to VB with equivalent syntax and logic. | (defn squeeze [s c]
(let [spans (partition-by #(= c %) s)
span-out (fn [span]
(if (= c (first span))
(str c)
(apply str span)))]
(apply str (map span-out spans))))
(defn test-squeeze [s c]
(let [out (squeeze s c)]
(println (format "Input: <<<%s>>> (len %d)\n" s (count s))
(format "becomes: <<<%s>>> (len %d)" out (count out)))))
| Imports System.Linq.Enumerable
Module Module1
Function Squeeze(s As String, c As Char) As String
If String.IsNullOrEmpty(s) Then
Return ""
End If
Return s(0) + New String(Range(1, s.Length - 1).Where(Function(i) s(i) <> c OrElse s(i) <> s(i - 1)).Select(Function(i) s(i)).ToArray())
End Function
Sub SqueezeAndPrint(s As String, c As Char)
Console.WriteLine("squeeze:
Console.WriteLine("old: {0} «««{1}»»»", s.Length, s)
s = Squeeze(s, c)
Console.WriteLine("new: {0} «««{1}»»»", s.Length, s)
End Sub
Sub Main()
Const QUOTE = """"
SqueezeAndPrint("", " ")
SqueezeAndPrint(QUOTE & "If I were two-faced, would I be wearing this one?" & QUOTE & " --- Abraham Lincoln ", "-")
SqueezeAndPrint("..1111111111111111111111111111111111111111111111111111111111111117777888", "7")
SqueezeAndPrint("I never give
Dim s = " --- Harry S Truman "
SqueezeAndPrint(s, " ")
SqueezeAndPrint(s, "-")
SqueezeAndPrint(s, "r")
End Sub
End Module
|
Preserve the algorithm and functionality while converting the code from Clojure to VB. | (defn squeeze [s c]
(let [spans (partition-by #(= c %) s)
span-out (fn [span]
(if (= c (first span))
(str c)
(apply str span)))]
(apply str (map span-out spans))))
(defn test-squeeze [s c]
(let [out (squeeze s c)]
(println (format "Input: <<<%s>>> (len %d)\n" s (count s))
(format "becomes: <<<%s>>> (len %d)" out (count out)))))
| 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 Clojure code snippet into Go without altering its behavior. | (defn squeeze [s c]
(let [spans (partition-by #(= c %) s)
span-out (fn [span]
(if (= c (first span))
(str c)
(apply str span)))]
(apply str (map span-out spans))))
(defn test-squeeze [s c]
(let [out (squeeze s c)]
(println (format "Input: <<<%s>>> (len %d)\n" s (count s))
(format "becomes: <<<%s>>> (len %d)" out (count out)))))
| 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 Clojure code in Go. | (defn squeeze [s c]
(let [spans (partition-by #(= c %) s)
span-out (fn [span]
(if (= c (first span))
(str c)
(apply str span)))]
(apply str (map span-out spans))))
(defn test-squeeze [s c]
(let [out (squeeze s c)]
(println (format "Input: <<<%s>>> (len %d)\n" s (count s))
(format "becomes: <<<%s>>> (len %d)" out (count out)))))
| package main
import "fmt"
func squeeze(s string, c rune) (string, int, int) {
r := []rune(s)
le, del := len(r), 0
for i := le - 2; i >= 0; i-- {
if r[i] == c && r[i] == r[i+1] {
copy(r[i:], r[i+1:])
del++
}
}
if del == 0 {
return s, le, le
}
r = r[:le-del]
return string(r), le, len(r)
}
func main() {
strings := []string{
"",
`"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln `,
"..1111111111111111111111111111111111111111111111111111111111111117777888",
"I never give 'em hell, I just tell the truth, and they think it's hell. ",
" --- Harry S Truman ",
"The better the 4-wheel drive, the further you'll be from help when ya get stuck!",
"headmistressship",
"aardvark",
"😍😀🙌💃😍😍😍🙌",
}
chars := [][]rune{{' '}, {'-'}, {'7'}, {'.'}, {' ', '-', 'r'}, {'e'}, {'s'}, {'a'}, {'😍'}}
for i, s := range strings {
for _, c := range chars[i] {
ss, olen, slen := squeeze(s, c)
fmt.Printf("specified character = %q\n", c)
fmt.Printf("original : length = %2d, string = «««%s»»»\n", olen, s)
fmt.Printf("squeezed : length = %2d, string = «««%s»»»\n\n", slen, ss)
}
}
}
|
Change the following D code into C without altering its purpose. | import std.stdio;
void squeezable(string s, char rune) {
writeln("squeeze: '", rune, "'");
writeln("old: <<<", s, ">>>, length = ", s.length);
write("new: <<<");
char last = '\0';
int len = 0;
foreach (c; s) {
if (c != last || c != rune) {
write(c);
len++;
}
last = c;
}
writeln(">>>, length = ", len);
writeln;
}
void main() {
squeezable(``, ' ');
squeezable(`"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln `, '-');
squeezable(`..1111111111111111111111111111111111111111111111111111111111111117777888`, '7');
squeezable(`I never give 'em hell, I just tell the truth, and they think it's hell. `, '.');
string s = ` --- Harry S Truman `;
squeezable(s, ' ');
squeezable(s, '-');
squeezable(s, 'r');
}
| #include<string.h>
#include<stdlib.h>
#include<stdio.h>
#define COLLAPSE 0
#define SQUEEZE 1
typedef struct charList{
char c;
struct charList *next;
} charList;
int strcmpi(char str1[100],char str2[100]){
int len1 = strlen(str1), len2 = strlen(str2), i;
if(len1!=len2){
return 1;
}
else{
for(i=0;i<len1;i++){
if((str1[i]>='A'&&str1[i]<='Z')&&(str2[i]>='a'&&str2[i]<='z')&&(str2[i]-65!=str1[i]))
return 1;
else if((str2[i]>='A'&&str2[i]<='Z')&&(str1[i]>='a'&&str1[i]<='z')&&(str1[i]-65!=str2[i]))
return 1;
else if(str1[i]!=str2[i])
return 1;
}
}
return 0;
}
charList *strToCharList(char* str){
int len = strlen(str),i;
charList *list, *iterator, *nextChar;
list = (charList*)malloc(sizeof(charList));
list->c = str[0];
list->next = NULL;
iterator = list;
for(i=1;i<len;i++){
nextChar = (charList*)malloc(sizeof(charList));
nextChar->c = str[i];
nextChar->next = NULL;
iterator->next = nextChar;
iterator = nextChar;
}
return list;
}
char* charListToString(charList* list){
charList* iterator = list;
int count = 0,i;
char* str;
while(iterator!=NULL){
count++;
iterator = iterator->next;
}
str = (char*)malloc((count+1)*sizeof(char));
iterator = list;
for(i=0;i<count;i++){
str[i] = iterator->c;
iterator = iterator->next;
}
free(list);
str[i] = '\0';
return str;
}
char* processString(char str[100],int operation, char squeezeChar){
charList *strList = strToCharList(str),*iterator = strList, *scout;
if(operation==SQUEEZE){
while(iterator!=NULL){
if(iterator->c==squeezeChar){
scout = iterator->next;
while(scout!=NULL && scout->c==squeezeChar){
iterator->next = scout->next;
scout->next = NULL;
free(scout);
scout = iterator->next;
}
}
iterator = iterator->next;
}
}
else{
while(iterator!=NULL && iterator->next!=NULL){
if(iterator->c == (iterator->next)->c){
scout = iterator->next;
squeezeChar = iterator->c;
while(scout!=NULL && scout->c==squeezeChar){
iterator->next = scout->next;
scout->next = NULL;
free(scout);
scout = iterator->next;
}
}
iterator = iterator->next;
}
}
return charListToString(strList);
}
void printResults(char originalString[100], char finalString[100], int operation, char squeezeChar){
if(operation==SQUEEZE){
printf("Specified Operation : SQUEEZE\nTarget Character : %c",squeezeChar);
}
else
printf("Specified Operation : COLLAPSE");
printf("\nOriginal %c%c%c%s%c%c%c\nLength : %d",174,174,174,originalString,175,175,175,(int)strlen(originalString));
printf("\nFinal %c%c%c%s%c%c%c\nLength : %d\n",174,174,174,finalString,175,175,175,(int)strlen(finalString));
}
int main(int argc, char** argv){
int operation;
char squeezeChar;
if(argc<3||argc>4){
printf("Usage : %s <SQUEEZE|COLLAPSE> <String to be processed> <Character to be squeezed, if operation is SQUEEZE>\n",argv[0]);
return 0;
}
if(strcmpi(argv[1],"SQUEEZE")==0 && argc!=4){
scanf("Please enter characted to be squeezed : %c",&squeezeChar);
operation = SQUEEZE;
}
else if(argc==4){
operation = SQUEEZE;
squeezeChar = argv[3][0];
}
else if(strcmpi(argv[1],"COLLAPSE")==0){
operation = COLLAPSE;
}
if(strlen(argv[2])<2){
printResults(argv[2],argv[2],operation,squeezeChar);
}
else{
printResults(argv[2],processString(argv[2],operation,squeezeChar),operation,squeezeChar);
}
return 0;
}
|
Port the following code from D to C with equivalent syntax and logic. | import std.stdio;
void squeezable(string s, char rune) {
writeln("squeeze: '", rune, "'");
writeln("old: <<<", s, ">>>, length = ", s.length);
write("new: <<<");
char last = '\0';
int len = 0;
foreach (c; s) {
if (c != last || c != rune) {
write(c);
len++;
}
last = c;
}
writeln(">>>, length = ", len);
writeln;
}
void main() {
squeezable(``, ' ');
squeezable(`"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln `, '-');
squeezable(`..1111111111111111111111111111111111111111111111111111111111111117777888`, '7');
squeezable(`I never give 'em hell, I just tell the truth, and they think it's hell. `, '.');
string s = ` --- Harry S Truman `;
squeezable(s, ' ');
squeezable(s, '-');
squeezable(s, 'r');
}
| #include<string.h>
#include<stdlib.h>
#include<stdio.h>
#define COLLAPSE 0
#define SQUEEZE 1
typedef struct charList{
char c;
struct charList *next;
} charList;
int strcmpi(char str1[100],char str2[100]){
int len1 = strlen(str1), len2 = strlen(str2), i;
if(len1!=len2){
return 1;
}
else{
for(i=0;i<len1;i++){
if((str1[i]>='A'&&str1[i]<='Z')&&(str2[i]>='a'&&str2[i]<='z')&&(str2[i]-65!=str1[i]))
return 1;
else if((str2[i]>='A'&&str2[i]<='Z')&&(str1[i]>='a'&&str1[i]<='z')&&(str1[i]-65!=str2[i]))
return 1;
else if(str1[i]!=str2[i])
return 1;
}
}
return 0;
}
charList *strToCharList(char* str){
int len = strlen(str),i;
charList *list, *iterator, *nextChar;
list = (charList*)malloc(sizeof(charList));
list->c = str[0];
list->next = NULL;
iterator = list;
for(i=1;i<len;i++){
nextChar = (charList*)malloc(sizeof(charList));
nextChar->c = str[i];
nextChar->next = NULL;
iterator->next = nextChar;
iterator = nextChar;
}
return list;
}
char* charListToString(charList* list){
charList* iterator = list;
int count = 0,i;
char* str;
while(iterator!=NULL){
count++;
iterator = iterator->next;
}
str = (char*)malloc((count+1)*sizeof(char));
iterator = list;
for(i=0;i<count;i++){
str[i] = iterator->c;
iterator = iterator->next;
}
free(list);
str[i] = '\0';
return str;
}
char* processString(char str[100],int operation, char squeezeChar){
charList *strList = strToCharList(str),*iterator = strList, *scout;
if(operation==SQUEEZE){
while(iterator!=NULL){
if(iterator->c==squeezeChar){
scout = iterator->next;
while(scout!=NULL && scout->c==squeezeChar){
iterator->next = scout->next;
scout->next = NULL;
free(scout);
scout = iterator->next;
}
}
iterator = iterator->next;
}
}
else{
while(iterator!=NULL && iterator->next!=NULL){
if(iterator->c == (iterator->next)->c){
scout = iterator->next;
squeezeChar = iterator->c;
while(scout!=NULL && scout->c==squeezeChar){
iterator->next = scout->next;
scout->next = NULL;
free(scout);
scout = iterator->next;
}
}
iterator = iterator->next;
}
}
return charListToString(strList);
}
void printResults(char originalString[100], char finalString[100], int operation, char squeezeChar){
if(operation==SQUEEZE){
printf("Specified Operation : SQUEEZE\nTarget Character : %c",squeezeChar);
}
else
printf("Specified Operation : COLLAPSE");
printf("\nOriginal %c%c%c%s%c%c%c\nLength : %d",174,174,174,originalString,175,175,175,(int)strlen(originalString));
printf("\nFinal %c%c%c%s%c%c%c\nLength : %d\n",174,174,174,finalString,175,175,175,(int)strlen(finalString));
}
int main(int argc, char** argv){
int operation;
char squeezeChar;
if(argc<3||argc>4){
printf("Usage : %s <SQUEEZE|COLLAPSE> <String to be processed> <Character to be squeezed, if operation is SQUEEZE>\n",argv[0]);
return 0;
}
if(strcmpi(argv[1],"SQUEEZE")==0 && argc!=4){
scanf("Please enter characted to be squeezed : %c",&squeezeChar);
operation = SQUEEZE;
}
else if(argc==4){
operation = SQUEEZE;
squeezeChar = argv[3][0];
}
else if(strcmpi(argv[1],"COLLAPSE")==0){
operation = COLLAPSE;
}
if(strlen(argv[2])<2){
printResults(argv[2],argv[2],operation,squeezeChar);
}
else{
printResults(argv[2],processString(argv[2],operation,squeezeChar),operation,squeezeChar);
}
return 0;
}
|
Transform the following D implementation into C#, maintaining the same output and logic. | import std.stdio;
void squeezable(string s, char rune) {
writeln("squeeze: '", rune, "'");
writeln("old: <<<", s, ">>>, length = ", s.length);
write("new: <<<");
char last = '\0';
int len = 0;
foreach (c; s) {
if (c != last || c != rune) {
write(c);
len++;
}
last = c;
}
writeln(">>>, length = ", len);
writeln;
}
void main() {
squeezable(``, ' ');
squeezable(`"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln `, '-');
squeezable(`..1111111111111111111111111111111111111111111111111111111111111117777888`, '7');
squeezable(`I never give 'em hell, I just tell the truth, and they think it's hell. `, '.');
string s = ` --- Harry S Truman `;
squeezable(s, ' ');
squeezable(s, '-');
squeezable(s, 'r');
}
| using System;
using static System.Linq.Enumerable;
public class Program
{
static void Main()
{
SqueezeAndPrint("", ' ');
SqueezeAndPrint("\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln ", '-');
SqueezeAndPrint("..1111111111111111111111111111111111111111111111111111111111111117777888", '7');
SqueezeAndPrint("I never give 'em hell, I just tell the truth, and they think it's hell. ", '.');
string s = " --- Harry S Truman ";
SqueezeAndPrint(s, ' ');
SqueezeAndPrint(s, '-');
SqueezeAndPrint(s, 'r');
}
static void SqueezeAndPrint(string s, char c) {
Console.WriteLine($"squeeze: '{c}'");
Console.WriteLine($"old: {s.Length} «««{s}»»»");
s = Squeeze(s, c);
Console.WriteLine($"new: {s.Length} «««{s}»»»");
}
static string Squeeze(string s, char c) => string.IsNullOrEmpty(s) ? "" :
s[0] + new string(Range(1, s.Length - 1).Where(i => s[i] != c || s[i] != s[i - 1]).Select(i => s[i]).ToArray());
}
|
Rewrite this program in C# while keeping its functionality equivalent to the D version. | import std.stdio;
void squeezable(string s, char rune) {
writeln("squeeze: '", rune, "'");
writeln("old: <<<", s, ">>>, length = ", s.length);
write("new: <<<");
char last = '\0';
int len = 0;
foreach (c; s) {
if (c != last || c != rune) {
write(c);
len++;
}
last = c;
}
writeln(">>>, length = ", len);
writeln;
}
void main() {
squeezable(``, ' ');
squeezable(`"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln `, '-');
squeezable(`..1111111111111111111111111111111111111111111111111111111111111117777888`, '7');
squeezable(`I never give 'em hell, I just tell the truth, and they think it's hell. `, '.');
string s = ` --- Harry S Truman `;
squeezable(s, ' ');
squeezable(s, '-');
squeezable(s, 'r');
}
| using System;
using static System.Linq.Enumerable;
public class Program
{
static void Main()
{
SqueezeAndPrint("", ' ');
SqueezeAndPrint("\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln ", '-');
SqueezeAndPrint("..1111111111111111111111111111111111111111111111111111111111111117777888", '7');
SqueezeAndPrint("I never give 'em hell, I just tell the truth, and they think it's hell. ", '.');
string s = " --- Harry S Truman ";
SqueezeAndPrint(s, ' ');
SqueezeAndPrint(s, '-');
SqueezeAndPrint(s, 'r');
}
static void SqueezeAndPrint(string s, char c) {
Console.WriteLine($"squeeze: '{c}'");
Console.WriteLine($"old: {s.Length} «««{s}»»»");
s = Squeeze(s, c);
Console.WriteLine($"new: {s.Length} «««{s}»»»");
}
static string Squeeze(string s, char c) => string.IsNullOrEmpty(s) ? "" :
s[0] + new string(Range(1, s.Length - 1).Where(i => s[i] != c || s[i] != s[i - 1]).Select(i => s[i]).ToArray());
}
|
Generate an equivalent C++ version of this D code. | import std.stdio;
void squeezable(string s, char rune) {
writeln("squeeze: '", rune, "'");
writeln("old: <<<", s, ">>>, length = ", s.length);
write("new: <<<");
char last = '\0';
int len = 0;
foreach (c; s) {
if (c != last || c != rune) {
write(c);
len++;
}
last = c;
}
writeln(">>>, length = ", len);
writeln;
}
void main() {
squeezable(``, ' ');
squeezable(`"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln `, '-');
squeezable(`..1111111111111111111111111111111111111111111111111111111111111117777888`, '7');
squeezable(`I never give 'em hell, I just tell the truth, and they think it's hell. `, '.');
string s = ` --- Harry S Truman `;
squeezable(s, ' ');
squeezable(s, '-');
squeezable(s, 'r');
}
| #include <algorithm>
#include <string>
#include <iostream>
template<typename char_type>
std::basic_string<char_type> squeeze(std::basic_string<char_type> str, char_type ch) {
auto i = std::unique(str.begin(), str.end(),
[ch](char_type a, char_type b) { return a == ch && b == ch; });
str.erase(i, str.end());
return str;
}
void test(const std::string& str, char ch) {
std::cout << "character: '" << ch << "'\n";
std::cout << "original: <<<" << str << ">>>, length: " << str.length() << '\n';
std::string squeezed(squeeze(str, ch));
std::cout << "result: <<<" << squeezed << ">>>, length: " << squeezed.length() << '\n';
std::cout << '\n';
}
int main(int argc, char** argv) {
test("", ' ');
test("\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln ", '-');
test("..1111111111111111111111111111111111111111111111111111111111111117777888", '7');
test("I never give 'em hell, I just tell the truth, and they think it's hell. ", '.');
std::string truman(" --- Harry S Truman ");
test(truman, ' ');
test(truman, '-');
test(truman, 'r');
return 0;
}
|
Please provide an equivalent version of this D code in C++. | import std.stdio;
void squeezable(string s, char rune) {
writeln("squeeze: '", rune, "'");
writeln("old: <<<", s, ">>>, length = ", s.length);
write("new: <<<");
char last = '\0';
int len = 0;
foreach (c; s) {
if (c != last || c != rune) {
write(c);
len++;
}
last = c;
}
writeln(">>>, length = ", len);
writeln;
}
void main() {
squeezable(``, ' ');
squeezable(`"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln `, '-');
squeezable(`..1111111111111111111111111111111111111111111111111111111111111117777888`, '7');
squeezable(`I never give 'em hell, I just tell the truth, and they think it's hell. `, '.');
string s = ` --- Harry S Truman `;
squeezable(s, ' ');
squeezable(s, '-');
squeezable(s, 'r');
}
| #include <algorithm>
#include <string>
#include <iostream>
template<typename char_type>
std::basic_string<char_type> squeeze(std::basic_string<char_type> str, char_type ch) {
auto i = std::unique(str.begin(), str.end(),
[ch](char_type a, char_type b) { return a == ch && b == ch; });
str.erase(i, str.end());
return str;
}
void test(const std::string& str, char ch) {
std::cout << "character: '" << ch << "'\n";
std::cout << "original: <<<" << str << ">>>, length: " << str.length() << '\n';
std::string squeezed(squeeze(str, ch));
std::cout << "result: <<<" << squeezed << ">>>, length: " << squeezed.length() << '\n';
std::cout << '\n';
}
int main(int argc, char** argv) {
test("", ' ');
test("\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln ", '-');
test("..1111111111111111111111111111111111111111111111111111111111111117777888", '7');
test("I never give 'em hell, I just tell the truth, and they think it's hell. ", '.');
std::string truman(" --- Harry S Truman ");
test(truman, ' ');
test(truman, '-');
test(truman, 'r');
return 0;
}
|
Can you help me rewrite this code in Java instead of D, keeping it the same logically? | import std.stdio;
void squeezable(string s, char rune) {
writeln("squeeze: '", rune, "'");
writeln("old: <<<", s, ">>>, length = ", s.length);
write("new: <<<");
char last = '\0';
int len = 0;
foreach (c; s) {
if (c != last || c != rune) {
write(c);
len++;
}
last = c;
}
writeln(">>>, length = ", len);
writeln;
}
void main() {
squeezable(``, ' ');
squeezable(`"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln `, '-');
squeezable(`..1111111111111111111111111111111111111111111111111111111111111117777888`, '7');
squeezable(`I never give 'em hell, I just tell the truth, and they think it's hell. `, '.');
string s = ` --- Harry S Truman `;
squeezable(s, ' ');
squeezable(s, '-');
squeezable(s, 'r');
}
|
public class StringSqueezable {
public static void main(String[] args) {
String[] testStrings = new String[] {
"",
"\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln ",
"..1111111111111111111111111111111111111111111111111111111111111117777888",
"I never give 'em hell, I just tell the truth, and they think it's hell. ",
" --- Harry S Truman ",
"122333444455555666666777777788888888999999999",
"The better the 4-wheel drive, the further you'll be from help when ya get stuck!",
"headmistressship"};
String[] testChar = new String[] {
" ",
"-",
"7",
".",
" -r",
"5",
"e",
"s"};
for ( int testNum = 0 ; testNum < testStrings.length ; testNum++ ) {
String s = testStrings[testNum];
for ( char c : testChar[testNum].toCharArray() ) {
String result = squeeze(s, c);
System.out.printf("use: '%c'%nold: %2d <<<%s>>>%nnew: %2d <<<%s>>>%n%n", c, s.length(), s, result.length(), result);
}
}
}
private static String squeeze(String in, char include) {
StringBuilder sb = new StringBuilder();
for ( int i = 0 ; i < in.length() ; i++ ) {
if ( i == 0 || in.charAt(i-1) != in.charAt(i) || (in.charAt(i-1) == in.charAt(i) && in.charAt(i) != include)) {
sb.append(in.charAt(i));
}
}
return sb.toString();
}
}
|
Rewrite the snippet below in Java so it works the same as the original D code. | import std.stdio;
void squeezable(string s, char rune) {
writeln("squeeze: '", rune, "'");
writeln("old: <<<", s, ">>>, length = ", s.length);
write("new: <<<");
char last = '\0';
int len = 0;
foreach (c; s) {
if (c != last || c != rune) {
write(c);
len++;
}
last = c;
}
writeln(">>>, length = ", len);
writeln;
}
void main() {
squeezable(``, ' ');
squeezable(`"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln `, '-');
squeezable(`..1111111111111111111111111111111111111111111111111111111111111117777888`, '7');
squeezable(`I never give 'em hell, I just tell the truth, and they think it's hell. `, '.');
string s = ` --- Harry S Truman `;
squeezable(s, ' ');
squeezable(s, '-');
squeezable(s, 'r');
}
|
public class StringSqueezable {
public static void main(String[] args) {
String[] testStrings = new String[] {
"",
"\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln ",
"..1111111111111111111111111111111111111111111111111111111111111117777888",
"I never give 'em hell, I just tell the truth, and they think it's hell. ",
" --- Harry S Truman ",
"122333444455555666666777777788888888999999999",
"The better the 4-wheel drive, the further you'll be from help when ya get stuck!",
"headmistressship"};
String[] testChar = new String[] {
" ",
"-",
"7",
".",
" -r",
"5",
"e",
"s"};
for ( int testNum = 0 ; testNum < testStrings.length ; testNum++ ) {
String s = testStrings[testNum];
for ( char c : testChar[testNum].toCharArray() ) {
String result = squeeze(s, c);
System.out.printf("use: '%c'%nold: %2d <<<%s>>>%nnew: %2d <<<%s>>>%n%n", c, s.length(), s, result.length(), result);
}
}
}
private static String squeeze(String in, char include) {
StringBuilder sb = new StringBuilder();
for ( int i = 0 ; i < in.length() ; i++ ) {
if ( i == 0 || in.charAt(i-1) != in.charAt(i) || (in.charAt(i-1) == in.charAt(i) && in.charAt(i) != include)) {
sb.append(in.charAt(i));
}
}
return sb.toString();
}
}
|
Rewrite the snippet below in Python so it works the same as the original D code. | import std.stdio;
void squeezable(string s, char rune) {
writeln("squeeze: '", rune, "'");
writeln("old: <<<", s, ">>>, length = ", s.length);
write("new: <<<");
char last = '\0';
int len = 0;
foreach (c; s) {
if (c != last || c != rune) {
write(c);
len++;
}
last = c;
}
writeln(">>>, length = ", len);
writeln;
}
void main() {
squeezable(``, ' ');
squeezable(`"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln `, '-');
squeezable(`..1111111111111111111111111111111111111111111111111111111111111117777888`, '7');
squeezable(`I never give 'em hell, I just tell the truth, and they think it's hell. `, '.');
string s = ` --- Harry S Truman `;
squeezable(s, ' ');
squeezable(s, '-');
squeezable(s, 'r');
}
| from itertools import groupby
def squeezer(s, txt):
return ''.join(item if item == s else ''.join(grp)
for item, grp in groupby(txt))
if __name__ == '__main__':
strings = [
"",
'"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln ',
"..1111111111111111111111111111111111111111111111111111111111111117777888",
"I never give 'em hell, I just tell the truth, and they think it's hell. ",
" --- Harry S Truman ",
"The better the 4-wheel drive, the further you'll be from help when ya get stuck!",
"headmistressship",
"aardvark",
"😍😀🙌💃😍😍😍🙌",
]
squeezers = ' ,-,7,., -r,e,s,a,😍'.split(',')
for txt, chars in zip(strings, squeezers):
this = "Original"
print(f"\n{this:14} Size: {len(txt)} «««{txt}»»»" )
for ch in chars:
this = f"Squeezer '{ch}'"
sqz = squeezer(ch, txt)
print(f"{this:>14} Size: {len(sqz)} «««{sqz}»»»" )
|
Write a version of this D function in Python with identical behavior. | import std.stdio;
void squeezable(string s, char rune) {
writeln("squeeze: '", rune, "'");
writeln("old: <<<", s, ">>>, length = ", s.length);
write("new: <<<");
char last = '\0';
int len = 0;
foreach (c; s) {
if (c != last || c != rune) {
write(c);
len++;
}
last = c;
}
writeln(">>>, length = ", len);
writeln;
}
void main() {
squeezable(``, ' ');
squeezable(`"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln `, '-');
squeezable(`..1111111111111111111111111111111111111111111111111111111111111117777888`, '7');
squeezable(`I never give 'em hell, I just tell the truth, and they think it's hell. `, '.');
string s = ` --- Harry S Truman `;
squeezable(s, ' ');
squeezable(s, '-');
squeezable(s, 'r');
}
| from itertools import groupby
def squeezer(s, txt):
return ''.join(item if item == s else ''.join(grp)
for item, grp in groupby(txt))
if __name__ == '__main__':
strings = [
"",
'"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln ',
"..1111111111111111111111111111111111111111111111111111111111111117777888",
"I never give 'em hell, I just tell the truth, and they think it's hell. ",
" --- Harry S Truman ",
"The better the 4-wheel drive, the further you'll be from help when ya get stuck!",
"headmistressship",
"aardvark",
"😍😀🙌💃😍😍😍🙌",
]
squeezers = ' ,-,7,., -r,e,s,a,😍'.split(',')
for txt, chars in zip(strings, squeezers):
this = "Original"
print(f"\n{this:14} Size: {len(txt)} «««{txt}»»»" )
for ch in chars:
this = f"Squeezer '{ch}'"
sqz = squeezer(ch, txt)
print(f"{this:>14} Size: {len(sqz)} «««{sqz}»»»" )
|
Convert this D snippet to VB and keep its semantics consistent. | import std.stdio;
void squeezable(string s, char rune) {
writeln("squeeze: '", rune, "'");
writeln("old: <<<", s, ">>>, length = ", s.length);
write("new: <<<");
char last = '\0';
int len = 0;
foreach (c; s) {
if (c != last || c != rune) {
write(c);
len++;
}
last = c;
}
writeln(">>>, length = ", len);
writeln;
}
void main() {
squeezable(``, ' ');
squeezable(`"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln `, '-');
squeezable(`..1111111111111111111111111111111111111111111111111111111111111117777888`, '7');
squeezable(`I never give 'em hell, I just tell the truth, and they think it's hell. `, '.');
string s = ` --- Harry S Truman `;
squeezable(s, ' ');
squeezable(s, '-');
squeezable(s, 'r');
}
| Imports System.Linq.Enumerable
Module Module1
Function Squeeze(s As String, c As Char) As String
If String.IsNullOrEmpty(s) Then
Return ""
End If
Return s(0) + New String(Range(1, s.Length - 1).Where(Function(i) s(i) <> c OrElse s(i) <> s(i - 1)).Select(Function(i) s(i)).ToArray())
End Function
Sub SqueezeAndPrint(s As String, c As Char)
Console.WriteLine("squeeze:
Console.WriteLine("old: {0} «««{1}»»»", s.Length, s)
s = Squeeze(s, c)
Console.WriteLine("new: {0} «««{1}»»»", s.Length, s)
End Sub
Sub Main()
Const QUOTE = """"
SqueezeAndPrint("", " ")
SqueezeAndPrint(QUOTE & "If I were two-faced, would I be wearing this one?" & QUOTE & " --- Abraham Lincoln ", "-")
SqueezeAndPrint("..1111111111111111111111111111111111111111111111111111111111111117777888", "7")
SqueezeAndPrint("I never give
Dim s = " --- Harry S Truman "
SqueezeAndPrint(s, " ")
SqueezeAndPrint(s, "-")
SqueezeAndPrint(s, "r")
End Sub
End Module
|
Rewrite the snippet below in VB so it works the same as the original D code. | import std.stdio;
void squeezable(string s, char rune) {
writeln("squeeze: '", rune, "'");
writeln("old: <<<", s, ">>>, length = ", s.length);
write("new: <<<");
char last = '\0';
int len = 0;
foreach (c; s) {
if (c != last || c != rune) {
write(c);
len++;
}
last = c;
}
writeln(">>>, length = ", len);
writeln;
}
void main() {
squeezable(``, ' ');
squeezable(`"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln `, '-');
squeezable(`..1111111111111111111111111111111111111111111111111111111111111117777888`, '7');
squeezable(`I never give 'em hell, I just tell the truth, and they think it's hell. `, '.');
string s = ` --- Harry S Truman `;
squeezable(s, ' ');
squeezable(s, '-');
squeezable(s, 'r');
}
| Imports System.Linq.Enumerable
Module Module1
Function Squeeze(s As String, c As Char) As String
If String.IsNullOrEmpty(s) Then
Return ""
End If
Return s(0) + New String(Range(1, s.Length - 1).Where(Function(i) s(i) <> c OrElse s(i) <> s(i - 1)).Select(Function(i) s(i)).ToArray())
End Function
Sub SqueezeAndPrint(s As String, c As Char)
Console.WriteLine("squeeze:
Console.WriteLine("old: {0} «««{1}»»»", s.Length, s)
s = Squeeze(s, c)
Console.WriteLine("new: {0} «««{1}»»»", s.Length, s)
End Sub
Sub Main()
Const QUOTE = """"
SqueezeAndPrint("", " ")
SqueezeAndPrint(QUOTE & "If I were two-faced, would I be wearing this one?" & QUOTE & " --- Abraham Lincoln ", "-")
SqueezeAndPrint("..1111111111111111111111111111111111111111111111111111111111111117777888", "7")
SqueezeAndPrint("I never give
Dim s = " --- Harry S Truman "
SqueezeAndPrint(s, " ")
SqueezeAndPrint(s, "-")
SqueezeAndPrint(s, "r")
End Sub
End Module
|
Can you help me rewrite this code in Go instead of D, keeping it the same logically? | import std.stdio;
void squeezable(string s, char rune) {
writeln("squeeze: '", rune, "'");
writeln("old: <<<", s, ">>>, length = ", s.length);
write("new: <<<");
char last = '\0';
int len = 0;
foreach (c; s) {
if (c != last || c != rune) {
write(c);
len++;
}
last = c;
}
writeln(">>>, length = ", len);
writeln;
}
void main() {
squeezable(``, ' ');
squeezable(`"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln `, '-');
squeezable(`..1111111111111111111111111111111111111111111111111111111111111117777888`, '7');
squeezable(`I never give 'em hell, I just tell the truth, and they think it's hell. `, '.');
string s = ` --- Harry S Truman `;
squeezable(s, ' ');
squeezable(s, '-');
squeezable(s, 'r');
}
| package main
import "fmt"
func squeeze(s string, c rune) (string, int, int) {
r := []rune(s)
le, del := len(r), 0
for i := le - 2; i >= 0; i-- {
if r[i] == c && r[i] == r[i+1] {
copy(r[i:], r[i+1:])
del++
}
}
if del == 0 {
return s, le, le
}
r = r[:le-del]
return string(r), le, len(r)
}
func main() {
strings := []string{
"",
`"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln `,
"..1111111111111111111111111111111111111111111111111111111111111117777888",
"I never give 'em hell, I just tell the truth, and they think it's hell. ",
" --- Harry S Truman ",
"The better the 4-wheel drive, the further you'll be from help when ya get stuck!",
"headmistressship",
"aardvark",
"😍😀🙌💃😍😍😍🙌",
}
chars := [][]rune{{' '}, {'-'}, {'7'}, {'.'}, {' ', '-', 'r'}, {'e'}, {'s'}, {'a'}, {'😍'}}
for i, s := range strings {
for _, c := range chars[i] {
ss, olen, slen := squeeze(s, c)
fmt.Printf("specified character = %q\n", c)
fmt.Printf("original : length = %2d, string = «««%s»»»\n", olen, s)
fmt.Printf("squeezed : length = %2d, string = «««%s»»»\n\n", slen, ss)
}
}
}
|
Port the provided D code into Go while preserving the original functionality. | import std.stdio;
void squeezable(string s, char rune) {
writeln("squeeze: '", rune, "'");
writeln("old: <<<", s, ">>>, length = ", s.length);
write("new: <<<");
char last = '\0';
int len = 0;
foreach (c; s) {
if (c != last || c != rune) {
write(c);
len++;
}
last = c;
}
writeln(">>>, length = ", len);
writeln;
}
void main() {
squeezable(``, ' ');
squeezable(`"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln `, '-');
squeezable(`..1111111111111111111111111111111111111111111111111111111111111117777888`, '7');
squeezable(`I never give 'em hell, I just tell the truth, and they think it's hell. `, '.');
string s = ` --- Harry S Truman `;
squeezable(s, ' ');
squeezable(s, '-');
squeezable(s, 'r');
}
| package main
import "fmt"
func squeeze(s string, c rune) (string, int, int) {
r := []rune(s)
le, del := len(r), 0
for i := le - 2; i >= 0; i-- {
if r[i] == c && r[i] == r[i+1] {
copy(r[i:], r[i+1:])
del++
}
}
if del == 0 {
return s, le, le
}
r = r[:le-del]
return string(r), le, len(r)
}
func main() {
strings := []string{
"",
`"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln `,
"..1111111111111111111111111111111111111111111111111111111111111117777888",
"I never give 'em hell, I just tell the truth, and they think it's hell. ",
" --- Harry S Truman ",
"The better the 4-wheel drive, the further you'll be from help when ya get stuck!",
"headmistressship",
"aardvark",
"😍😀🙌💃😍😍😍🙌",
}
chars := [][]rune{{' '}, {'-'}, {'7'}, {'.'}, {' ', '-', 'r'}, {'e'}, {'s'}, {'a'}, {'😍'}}
for i, s := range strings {
for _, c := range chars[i] {
ss, olen, slen := squeeze(s, c)
fmt.Printf("specified character = %q\n", c)
fmt.Printf("original : length = %2d, string = «««%s»»»\n", olen, s)
fmt.Printf("squeezed : length = %2d, string = «««%s»»»\n\n", slen, ss)
}
}
}
|
Generate an equivalent C version of this Delphi code. | program Determine_if_a_string_is_squeezable;
uses
System.SysUtils;
var
TestStrings: TArray<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'];
TestChar: TArray<string> = [' ', '-', '7', '.', ' -r', '5', 'e', 's'];
function squeeze(s: string; include: char): string;
begin
var sb := TStringBuilder.Create;
for var i := 1 to s.Length do
begin
if (i = 1) or (s[i - 1] <> s[i]) or ((s[i - 1] = s[i]) and (s[i] <> include)) then
sb.Append(s[i]
end;
Result := sb.ToString;
sb.Free;
end;
begin
for var testNum := 0 to high(TestStrings) do
begin
var s := TestStrings[testNum];
for var c in TestChar[testNum] do
begin
var result: string := squeeze(s, c);
writeln(format('use: "%s"'#10'old: %2d <<<%s>>>'#10'new: %2d <<<%s>>>'#10, [c,
s.Length, s, result.length, result]));
end;
end;
readln;
end.
| #include<string.h>
#include<stdlib.h>
#include<stdio.h>
#define COLLAPSE 0
#define SQUEEZE 1
typedef struct charList{
char c;
struct charList *next;
} charList;
int strcmpi(char str1[100],char str2[100]){
int len1 = strlen(str1), len2 = strlen(str2), i;
if(len1!=len2){
return 1;
}
else{
for(i=0;i<len1;i++){
if((str1[i]>='A'&&str1[i]<='Z')&&(str2[i]>='a'&&str2[i]<='z')&&(str2[i]-65!=str1[i]))
return 1;
else if((str2[i]>='A'&&str2[i]<='Z')&&(str1[i]>='a'&&str1[i]<='z')&&(str1[i]-65!=str2[i]))
return 1;
else if(str1[i]!=str2[i])
return 1;
}
}
return 0;
}
charList *strToCharList(char* str){
int len = strlen(str),i;
charList *list, *iterator, *nextChar;
list = (charList*)malloc(sizeof(charList));
list->c = str[0];
list->next = NULL;
iterator = list;
for(i=1;i<len;i++){
nextChar = (charList*)malloc(sizeof(charList));
nextChar->c = str[i];
nextChar->next = NULL;
iterator->next = nextChar;
iterator = nextChar;
}
return list;
}
char* charListToString(charList* list){
charList* iterator = list;
int count = 0,i;
char* str;
while(iterator!=NULL){
count++;
iterator = iterator->next;
}
str = (char*)malloc((count+1)*sizeof(char));
iterator = list;
for(i=0;i<count;i++){
str[i] = iterator->c;
iterator = iterator->next;
}
free(list);
str[i] = '\0';
return str;
}
char* processString(char str[100],int operation, char squeezeChar){
charList *strList = strToCharList(str),*iterator = strList, *scout;
if(operation==SQUEEZE){
while(iterator!=NULL){
if(iterator->c==squeezeChar){
scout = iterator->next;
while(scout!=NULL && scout->c==squeezeChar){
iterator->next = scout->next;
scout->next = NULL;
free(scout);
scout = iterator->next;
}
}
iterator = iterator->next;
}
}
else{
while(iterator!=NULL && iterator->next!=NULL){
if(iterator->c == (iterator->next)->c){
scout = iterator->next;
squeezeChar = iterator->c;
while(scout!=NULL && scout->c==squeezeChar){
iterator->next = scout->next;
scout->next = NULL;
free(scout);
scout = iterator->next;
}
}
iterator = iterator->next;
}
}
return charListToString(strList);
}
void printResults(char originalString[100], char finalString[100], int operation, char squeezeChar){
if(operation==SQUEEZE){
printf("Specified Operation : SQUEEZE\nTarget Character : %c",squeezeChar);
}
else
printf("Specified Operation : COLLAPSE");
printf("\nOriginal %c%c%c%s%c%c%c\nLength : %d",174,174,174,originalString,175,175,175,(int)strlen(originalString));
printf("\nFinal %c%c%c%s%c%c%c\nLength : %d\n",174,174,174,finalString,175,175,175,(int)strlen(finalString));
}
int main(int argc, char** argv){
int operation;
char squeezeChar;
if(argc<3||argc>4){
printf("Usage : %s <SQUEEZE|COLLAPSE> <String to be processed> <Character to be squeezed, if operation is SQUEEZE>\n",argv[0]);
return 0;
}
if(strcmpi(argv[1],"SQUEEZE")==0 && argc!=4){
scanf("Please enter characted to be squeezed : %c",&squeezeChar);
operation = SQUEEZE;
}
else if(argc==4){
operation = SQUEEZE;
squeezeChar = argv[3][0];
}
else if(strcmpi(argv[1],"COLLAPSE")==0){
operation = COLLAPSE;
}
if(strlen(argv[2])<2){
printResults(argv[2],argv[2],operation,squeezeChar);
}
else{
printResults(argv[2],processString(argv[2],operation,squeezeChar),operation,squeezeChar);
}
return 0;
}
|
Rewrite the snippet below in C so it works the same as the original Delphi code. | program Determine_if_a_string_is_squeezable;
uses
System.SysUtils;
var
TestStrings: TArray<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'];
TestChar: TArray<string> = [' ', '-', '7', '.', ' -r', '5', 'e', 's'];
function squeeze(s: string; include: char): string;
begin
var sb := TStringBuilder.Create;
for var i := 1 to s.Length do
begin
if (i = 1) or (s[i - 1] <> s[i]) or ((s[i - 1] = s[i]) and (s[i] <> include)) then
sb.Append(s[i]
end;
Result := sb.ToString;
sb.Free;
end;
begin
for var testNum := 0 to high(TestStrings) do
begin
var s := TestStrings[testNum];
for var c in TestChar[testNum] do
begin
var result: string := squeeze(s, c);
writeln(format('use: "%s"'#10'old: %2d <<<%s>>>'#10'new: %2d <<<%s>>>'#10, [c,
s.Length, s, result.length, result]));
end;
end;
readln;
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;
}
|
Can you help me rewrite this code in C# instead of Delphi, keeping it the same logically? | program Determine_if_a_string_is_squeezable;
uses
System.SysUtils;
var
TestStrings: TArray<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'];
TestChar: TArray<string> = [' ', '-', '7', '.', ' -r', '5', 'e', 's'];
function squeeze(s: string; include: char): string;
begin
var sb := TStringBuilder.Create;
for var i := 1 to s.Length do
begin
if (i = 1) or (s[i - 1] <> s[i]) or ((s[i - 1] = s[i]) and (s[i] <> include)) then
sb.Append(s[i]
end;
Result := sb.ToString;
sb.Free;
end;
begin
for var testNum := 0 to high(TestStrings) do
begin
var s := TestStrings[testNum];
for var c in TestChar[testNum] do
begin
var result: string := squeeze(s, c);
writeln(format('use: "%s"'#10'old: %2d <<<%s>>>'#10'new: %2d <<<%s>>>'#10, [c,
s.Length, s, result.length, result]));
end;
end;
readln;
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());
}
|
Change the programming language of this snippet from Delphi to C# without modifying what it does. | program Determine_if_a_string_is_squeezable;
uses
System.SysUtils;
var
TestStrings: TArray<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'];
TestChar: TArray<string> = [' ', '-', '7', '.', ' -r', '5', 'e', 's'];
function squeeze(s: string; include: char): string;
begin
var sb := TStringBuilder.Create;
for var i := 1 to s.Length do
begin
if (i = 1) or (s[i - 1] <> s[i]) or ((s[i - 1] = s[i]) and (s[i] <> include)) then
sb.Append(s[i]
end;
Result := sb.ToString;
sb.Free;
end;
begin
for var testNum := 0 to high(TestStrings) do
begin
var s := TestStrings[testNum];
for var c in TestChar[testNum] do
begin
var result: string := squeeze(s, c);
writeln(format('use: "%s"'#10'old: %2d <<<%s>>>'#10'new: %2d <<<%s>>>'#10, [c,
s.Length, s, result.length, result]));
end;
end;
readln;
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 Delphi implementation into C++, maintaining the same output and logic. | program Determine_if_a_string_is_squeezable;
uses
System.SysUtils;
var
TestStrings: TArray<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'];
TestChar: TArray<string> = [' ', '-', '7', '.', ' -r', '5', 'e', 's'];
function squeeze(s: string; include: char): string;
begin
var sb := TStringBuilder.Create;
for var i := 1 to s.Length do
begin
if (i = 1) or (s[i - 1] <> s[i]) or ((s[i - 1] = s[i]) and (s[i] <> include)) then
sb.Append(s[i]
end;
Result := sb.ToString;
sb.Free;
end;
begin
for var testNum := 0 to high(TestStrings) do
begin
var s := TestStrings[testNum];
for var c in TestChar[testNum] do
begin
var result: string := squeeze(s, c);
writeln(format('use: "%s"'#10'old: %2d <<<%s>>>'#10'new: %2d <<<%s>>>'#10, [c,
s.Length, s, result.length, result]));
end;
end;
readln;
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;
}
|
Convert this Delphi snippet to C++ and keep its semantics consistent. | program Determine_if_a_string_is_squeezable;
uses
System.SysUtils;
var
TestStrings: TArray<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'];
TestChar: TArray<string> = [' ', '-', '7', '.', ' -r', '5', 'e', 's'];
function squeeze(s: string; include: char): string;
begin
var sb := TStringBuilder.Create;
for var i := 1 to s.Length do
begin
if (i = 1) or (s[i - 1] <> s[i]) or ((s[i - 1] = s[i]) and (s[i] <> include)) then
sb.Append(s[i]
end;
Result := sb.ToString;
sb.Free;
end;
begin
for var testNum := 0 to high(TestStrings) do
begin
var s := TestStrings[testNum];
for var c in TestChar[testNum] do
begin
var result: string := squeeze(s, c);
writeln(format('use: "%s"'#10'old: %2d <<<%s>>>'#10'new: %2d <<<%s>>>'#10, [c,
s.Length, s, result.length, result]));
end;
end;
readln;
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;
}
|
Please provide an equivalent version of this Delphi code in Java. | program Determine_if_a_string_is_squeezable;
uses
System.SysUtils;
var
TestStrings: TArray<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'];
TestChar: TArray<string> = [' ', '-', '7', '.', ' -r', '5', 'e', 's'];
function squeeze(s: string; include: char): string;
begin
var sb := TStringBuilder.Create;
for var i := 1 to s.Length do
begin
if (i = 1) or (s[i - 1] <> s[i]) or ((s[i - 1] = s[i]) and (s[i] <> include)) then
sb.Append(s[i]
end;
Result := sb.ToString;
sb.Free;
end;
begin
for var testNum := 0 to high(TestStrings) do
begin
var s := TestStrings[testNum];
for var c in TestChar[testNum] do
begin
var result: string := squeeze(s, c);
writeln(format('use: "%s"'#10'old: %2d <<<%s>>>'#10'new: %2d <<<%s>>>'#10, [c,
s.Length, s, result.length, result]));
end;
end;
readln;
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();
}
}
|
Keep all operations the same but rewrite the snippet in Java. | program Determine_if_a_string_is_squeezable;
uses
System.SysUtils;
var
TestStrings: TArray<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'];
TestChar: TArray<string> = [' ', '-', '7', '.', ' -r', '5', 'e', 's'];
function squeeze(s: string; include: char): string;
begin
var sb := TStringBuilder.Create;
for var i := 1 to s.Length do
begin
if (i = 1) or (s[i - 1] <> s[i]) or ((s[i - 1] = s[i]) and (s[i] <> include)) then
sb.Append(s[i]
end;
Result := sb.ToString;
sb.Free;
end;
begin
for var testNum := 0 to high(TestStrings) do
begin
var s := TestStrings[testNum];
for var c in TestChar[testNum] do
begin
var result: string := squeeze(s, c);
writeln(format('use: "%s"'#10'old: %2d <<<%s>>>'#10'new: %2d <<<%s>>>'#10, [c,
s.Length, s, result.length, result]));
end;
end;
readln;
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();
}
}
|
Translate this program into Python but keep the logic exactly as in Delphi. | program Determine_if_a_string_is_squeezable;
uses
System.SysUtils;
var
TestStrings: TArray<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'];
TestChar: TArray<string> = [' ', '-', '7', '.', ' -r', '5', 'e', 's'];
function squeeze(s: string; include: char): string;
begin
var sb := TStringBuilder.Create;
for var i := 1 to s.Length do
begin
if (i = 1) or (s[i - 1] <> s[i]) or ((s[i - 1] = s[i]) and (s[i] <> include)) then
sb.Append(s[i]
end;
Result := sb.ToString;
sb.Free;
end;
begin
for var testNum := 0 to high(TestStrings) do
begin
var s := TestStrings[testNum];
for var c in TestChar[testNum] do
begin
var result: string := squeeze(s, c);
writeln(format('use: "%s"'#10'old: %2d <<<%s>>>'#10'new: %2d <<<%s>>>'#10, [c,
s.Length, s, result.length, result]));
end;
end;
readln;
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 Delphi code into Python while preserving the original functionality. | program Determine_if_a_string_is_squeezable;
uses
System.SysUtils;
var
TestStrings: TArray<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'];
TestChar: TArray<string> = [' ', '-', '7', '.', ' -r', '5', 'e', 's'];
function squeeze(s: string; include: char): string;
begin
var sb := TStringBuilder.Create;
for var i := 1 to s.Length do
begin
if (i = 1) or (s[i - 1] <> s[i]) or ((s[i - 1] = s[i]) and (s[i] <> include)) then
sb.Append(s[i]
end;
Result := sb.ToString;
sb.Free;
end;
begin
for var testNum := 0 to high(TestStrings) do
begin
var s := TestStrings[testNum];
for var c in TestChar[testNum] do
begin
var result: string := squeeze(s, c);
writeln(format('use: "%s"'#10'old: %2d <<<%s>>>'#10'new: %2d <<<%s>>>'#10, [c,
s.Length, s, result.length, result]));
end;
end;
readln;
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}»»»" )
|
Rewrite the snippet below in VB so it works the same as the original Delphi code. | program Determine_if_a_string_is_squeezable;
uses
System.SysUtils;
var
TestStrings: TArray<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'];
TestChar: TArray<string> = [' ', '-', '7', '.', ' -r', '5', 'e', 's'];
function squeeze(s: string; include: char): string;
begin
var sb := TStringBuilder.Create;
for var i := 1 to s.Length do
begin
if (i = 1) or (s[i - 1] <> s[i]) or ((s[i - 1] = s[i]) and (s[i] <> include)) then
sb.Append(s[i]
end;
Result := sb.ToString;
sb.Free;
end;
begin
for var testNum := 0 to high(TestStrings) do
begin
var s := TestStrings[testNum];
for var c in TestChar[testNum] do
begin
var result: string := squeeze(s, c);
writeln(format('use: "%s"'#10'old: %2d <<<%s>>>'#10'new: %2d <<<%s>>>'#10, [c,
s.Length, s, result.length, result]));
end;
end;
readln;
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
|
Please provide an equivalent version of this Delphi code in VB. | program Determine_if_a_string_is_squeezable;
uses
System.SysUtils;
var
TestStrings: TArray<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'];
TestChar: TArray<string> = [' ', '-', '7', '.', ' -r', '5', 'e', 's'];
function squeeze(s: string; include: char): string;
begin
var sb := TStringBuilder.Create;
for var i := 1 to s.Length do
begin
if (i = 1) or (s[i - 1] <> s[i]) or ((s[i - 1] = s[i]) and (s[i] <> include)) then
sb.Append(s[i]
end;
Result := sb.ToString;
sb.Free;
end;
begin
for var testNum := 0 to high(TestStrings) do
begin
var s := TestStrings[testNum];
for var c in TestChar[testNum] do
begin
var result: string := squeeze(s, c);
writeln(format('use: "%s"'#10'old: %2d <<<%s>>>'#10'new: %2d <<<%s>>>'#10, [c,
s.Length, s, result.length, result]));
end;
end;
readln;
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
|
Maintain the same structure and functionality when rewriting this code in Go. | program Determine_if_a_string_is_squeezable;
uses
System.SysUtils;
var
TestStrings: TArray<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'];
TestChar: TArray<string> = [' ', '-', '7', '.', ' -r', '5', 'e', 's'];
function squeeze(s: string; include: char): string;
begin
var sb := TStringBuilder.Create;
for var i := 1 to s.Length do
begin
if (i = 1) or (s[i - 1] <> s[i]) or ((s[i - 1] = s[i]) and (s[i] <> include)) then
sb.Append(s[i]
end;
Result := sb.ToString;
sb.Free;
end;
begin
for var testNum := 0 to high(TestStrings) do
begin
var s := TestStrings[testNum];
for var c in TestChar[testNum] do
begin
var result: string := squeeze(s, c);
writeln(format('use: "%s"'#10'old: %2d <<<%s>>>'#10'new: %2d <<<%s>>>'#10, [c,
s.Length, s, result.length, result]));
end;
end;
readln;
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 Delphi code in Go. | program Determine_if_a_string_is_squeezable;
uses
System.SysUtils;
var
TestStrings: TArray<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'];
TestChar: TArray<string> = [' ', '-', '7', '.', ' -r', '5', 'e', 's'];
function squeeze(s: string; include: char): string;
begin
var sb := TStringBuilder.Create;
for var i := 1 to s.Length do
begin
if (i = 1) or (s[i - 1] <> s[i]) or ((s[i - 1] = s[i]) and (s[i] <> include)) then
sb.Append(s[i]
end;
Result := sb.ToString;
sb.Free;
end;
begin
for var testNum := 0 to high(TestStrings) do
begin
var s := TestStrings[testNum];
for var c in TestChar[testNum] do
begin
var result: string := squeeze(s, c);
writeln(format('use: "%s"'#10'old: %2d <<<%s>>>'#10'new: %2d <<<%s>>>'#10, [c,
s.Length, s, result.length, result]));
end;
end;
readln;
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 F# snippet without changing its computational steps. |
let squeeze n i=if String.length n=0 then None else
let fN=let mutable g=n.[0] in (fun n->if n=i && n=g then false else g<-n; true)
let fG=n.[0..0]+System.String(n.[1..].ToCharArray()|>Array.filter fN)
if fG.Length=n.Length then None else Some fG
let isSqueezable n g=match squeeze n g with
Some i->printfn "%A squeezes <<<%s>>> (length %d) to <<<%s>>> (length %d)" g n n.Length i i.Length
|_->printfn "%A does not squeeze <<<%s>>> (length %d)" g n n.Length
isSqueezable "" ' '
isSqueezable "\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln " '-'
isSqueezable "..1111111111111111111111111111111111111111111111111111111111111117777888" '7'
isSqueezable "I never give 'em hell, I just tell the truth, and they think it's hell. " '.'
let fN=isSqueezable " --- Harry S Truman " in fN ' '; fN '-'; fN 'r'
| #include<string.h>
#include<stdlib.h>
#include<stdio.h>
#define COLLAPSE 0
#define SQUEEZE 1
typedef struct charList{
char c;
struct charList *next;
} charList;
int strcmpi(char str1[100],char str2[100]){
int len1 = strlen(str1), len2 = strlen(str2), i;
if(len1!=len2){
return 1;
}
else{
for(i=0;i<len1;i++){
if((str1[i]>='A'&&str1[i]<='Z')&&(str2[i]>='a'&&str2[i]<='z')&&(str2[i]-65!=str1[i]))
return 1;
else if((str2[i]>='A'&&str2[i]<='Z')&&(str1[i]>='a'&&str1[i]<='z')&&(str1[i]-65!=str2[i]))
return 1;
else if(str1[i]!=str2[i])
return 1;
}
}
return 0;
}
charList *strToCharList(char* str){
int len = strlen(str),i;
charList *list, *iterator, *nextChar;
list = (charList*)malloc(sizeof(charList));
list->c = str[0];
list->next = NULL;
iterator = list;
for(i=1;i<len;i++){
nextChar = (charList*)malloc(sizeof(charList));
nextChar->c = str[i];
nextChar->next = NULL;
iterator->next = nextChar;
iterator = nextChar;
}
return list;
}
char* charListToString(charList* list){
charList* iterator = list;
int count = 0,i;
char* str;
while(iterator!=NULL){
count++;
iterator = iterator->next;
}
str = (char*)malloc((count+1)*sizeof(char));
iterator = list;
for(i=0;i<count;i++){
str[i] = iterator->c;
iterator = iterator->next;
}
free(list);
str[i] = '\0';
return str;
}
char* processString(char str[100],int operation, char squeezeChar){
charList *strList = strToCharList(str),*iterator = strList, *scout;
if(operation==SQUEEZE){
while(iterator!=NULL){
if(iterator->c==squeezeChar){
scout = iterator->next;
while(scout!=NULL && scout->c==squeezeChar){
iterator->next = scout->next;
scout->next = NULL;
free(scout);
scout = iterator->next;
}
}
iterator = iterator->next;
}
}
else{
while(iterator!=NULL && iterator->next!=NULL){
if(iterator->c == (iterator->next)->c){
scout = iterator->next;
squeezeChar = iterator->c;
while(scout!=NULL && scout->c==squeezeChar){
iterator->next = scout->next;
scout->next = NULL;
free(scout);
scout = iterator->next;
}
}
iterator = iterator->next;
}
}
return charListToString(strList);
}
void printResults(char originalString[100], char finalString[100], int operation, char squeezeChar){
if(operation==SQUEEZE){
printf("Specified Operation : SQUEEZE\nTarget Character : %c",squeezeChar);
}
else
printf("Specified Operation : COLLAPSE");
printf("\nOriginal %c%c%c%s%c%c%c\nLength : %d",174,174,174,originalString,175,175,175,(int)strlen(originalString));
printf("\nFinal %c%c%c%s%c%c%c\nLength : %d\n",174,174,174,finalString,175,175,175,(int)strlen(finalString));
}
int main(int argc, char** argv){
int operation;
char squeezeChar;
if(argc<3||argc>4){
printf("Usage : %s <SQUEEZE|COLLAPSE> <String to be processed> <Character to be squeezed, if operation is SQUEEZE>\n",argv[0]);
return 0;
}
if(strcmpi(argv[1],"SQUEEZE")==0 && argc!=4){
scanf("Please enter characted to be squeezed : %c",&squeezeChar);
operation = SQUEEZE;
}
else if(argc==4){
operation = SQUEEZE;
squeezeChar = argv[3][0];
}
else if(strcmpi(argv[1],"COLLAPSE")==0){
operation = COLLAPSE;
}
if(strlen(argv[2])<2){
printResults(argv[2],argv[2],operation,squeezeChar);
}
else{
printResults(argv[2],processString(argv[2],operation,squeezeChar),operation,squeezeChar);
}
return 0;
}
|
Convert the following code from F# to C, ensuring the logic remains intact. |
let squeeze n i=if String.length n=0 then None else
let fN=let mutable g=n.[0] in (fun n->if n=i && n=g then false else g<-n; true)
let fG=n.[0..0]+System.String(n.[1..].ToCharArray()|>Array.filter fN)
if fG.Length=n.Length then None else Some fG
let isSqueezable n g=match squeeze n g with
Some i->printfn "%A squeezes <<<%s>>> (length %d) to <<<%s>>> (length %d)" g n n.Length i i.Length
|_->printfn "%A does not squeeze <<<%s>>> (length %d)" g n n.Length
isSqueezable "" ' '
isSqueezable "\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln " '-'
isSqueezable "..1111111111111111111111111111111111111111111111111111111111111117777888" '7'
isSqueezable "I never give 'em hell, I just tell the truth, and they think it's hell. " '.'
let fN=isSqueezable " --- Harry S Truman " in fN ' '; fN '-'; fN 'r'
| #include<string.h>
#include<stdlib.h>
#include<stdio.h>
#define COLLAPSE 0
#define SQUEEZE 1
typedef struct charList{
char c;
struct charList *next;
} charList;
int strcmpi(char str1[100],char str2[100]){
int len1 = strlen(str1), len2 = strlen(str2), i;
if(len1!=len2){
return 1;
}
else{
for(i=0;i<len1;i++){
if((str1[i]>='A'&&str1[i]<='Z')&&(str2[i]>='a'&&str2[i]<='z')&&(str2[i]-65!=str1[i]))
return 1;
else if((str2[i]>='A'&&str2[i]<='Z')&&(str1[i]>='a'&&str1[i]<='z')&&(str1[i]-65!=str2[i]))
return 1;
else if(str1[i]!=str2[i])
return 1;
}
}
return 0;
}
charList *strToCharList(char* str){
int len = strlen(str),i;
charList *list, *iterator, *nextChar;
list = (charList*)malloc(sizeof(charList));
list->c = str[0];
list->next = NULL;
iterator = list;
for(i=1;i<len;i++){
nextChar = (charList*)malloc(sizeof(charList));
nextChar->c = str[i];
nextChar->next = NULL;
iterator->next = nextChar;
iterator = nextChar;
}
return list;
}
char* charListToString(charList* list){
charList* iterator = list;
int count = 0,i;
char* str;
while(iterator!=NULL){
count++;
iterator = iterator->next;
}
str = (char*)malloc((count+1)*sizeof(char));
iterator = list;
for(i=0;i<count;i++){
str[i] = iterator->c;
iterator = iterator->next;
}
free(list);
str[i] = '\0';
return str;
}
char* processString(char str[100],int operation, char squeezeChar){
charList *strList = strToCharList(str),*iterator = strList, *scout;
if(operation==SQUEEZE){
while(iterator!=NULL){
if(iterator->c==squeezeChar){
scout = iterator->next;
while(scout!=NULL && scout->c==squeezeChar){
iterator->next = scout->next;
scout->next = NULL;
free(scout);
scout = iterator->next;
}
}
iterator = iterator->next;
}
}
else{
while(iterator!=NULL && iterator->next!=NULL){
if(iterator->c == (iterator->next)->c){
scout = iterator->next;
squeezeChar = iterator->c;
while(scout!=NULL && scout->c==squeezeChar){
iterator->next = scout->next;
scout->next = NULL;
free(scout);
scout = iterator->next;
}
}
iterator = iterator->next;
}
}
return charListToString(strList);
}
void printResults(char originalString[100], char finalString[100], int operation, char squeezeChar){
if(operation==SQUEEZE){
printf("Specified Operation : SQUEEZE\nTarget Character : %c",squeezeChar);
}
else
printf("Specified Operation : COLLAPSE");
printf("\nOriginal %c%c%c%s%c%c%c\nLength : %d",174,174,174,originalString,175,175,175,(int)strlen(originalString));
printf("\nFinal %c%c%c%s%c%c%c\nLength : %d\n",174,174,174,finalString,175,175,175,(int)strlen(finalString));
}
int main(int argc, char** argv){
int operation;
char squeezeChar;
if(argc<3||argc>4){
printf("Usage : %s <SQUEEZE|COLLAPSE> <String to be processed> <Character to be squeezed, if operation is SQUEEZE>\n",argv[0]);
return 0;
}
if(strcmpi(argv[1],"SQUEEZE")==0 && argc!=4){
scanf("Please enter characted to be squeezed : %c",&squeezeChar);
operation = SQUEEZE;
}
else if(argc==4){
operation = SQUEEZE;
squeezeChar = argv[3][0];
}
else if(strcmpi(argv[1],"COLLAPSE")==0){
operation = COLLAPSE;
}
if(strlen(argv[2])<2){
printResults(argv[2],argv[2],operation,squeezeChar);
}
else{
printResults(argv[2],processString(argv[2],operation,squeezeChar),operation,squeezeChar);
}
return 0;
}
|
Ensure the translated C# code behaves exactly like the original F# snippet. |
let squeeze n i=if String.length n=0 then None else
let fN=let mutable g=n.[0] in (fun n->if n=i && n=g then false else g<-n; true)
let fG=n.[0..0]+System.String(n.[1..].ToCharArray()|>Array.filter fN)
if fG.Length=n.Length then None else Some fG
let isSqueezable n g=match squeeze n g with
Some i->printfn "%A squeezes <<<%s>>> (length %d) to <<<%s>>> (length %d)" g n n.Length i i.Length
|_->printfn "%A does not squeeze <<<%s>>> (length %d)" g n n.Length
isSqueezable "" ' '
isSqueezable "\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln " '-'
isSqueezable "..1111111111111111111111111111111111111111111111111111111111111117777888" '7'
isSqueezable "I never give 'em hell, I just tell the truth, and they think it's hell. " '.'
let fN=isSqueezable " --- Harry S Truman " in fN ' '; fN '-'; fN 'r'
| using System;
using static System.Linq.Enumerable;
public class Program
{
static void Main()
{
SqueezeAndPrint("", ' ');
SqueezeAndPrint("\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln ", '-');
SqueezeAndPrint("..1111111111111111111111111111111111111111111111111111111111111117777888", '7');
SqueezeAndPrint("I never give 'em hell, I just tell the truth, and they think it's hell. ", '.');
string s = " --- Harry S Truman ";
SqueezeAndPrint(s, ' ');
SqueezeAndPrint(s, '-');
SqueezeAndPrint(s, 'r');
}
static void SqueezeAndPrint(string s, char c) {
Console.WriteLine($"squeeze: '{c}'");
Console.WriteLine($"old: {s.Length} «««{s}»»»");
s = Squeeze(s, c);
Console.WriteLine($"new: {s.Length} «««{s}»»»");
}
static string Squeeze(string s, char c) => string.IsNullOrEmpty(s) ? "" :
s[0] + new string(Range(1, s.Length - 1).Where(i => s[i] != c || s[i] != s[i - 1]).Select(i => s[i]).ToArray());
}
|
Rewrite the snippet below in C# so it works the same as the original F# code. |
let squeeze n i=if String.length n=0 then None else
let fN=let mutable g=n.[0] in (fun n->if n=i && n=g then false else g<-n; true)
let fG=n.[0..0]+System.String(n.[1..].ToCharArray()|>Array.filter fN)
if fG.Length=n.Length then None else Some fG
let isSqueezable n g=match squeeze n g with
Some i->printfn "%A squeezes <<<%s>>> (length %d) to <<<%s>>> (length %d)" g n n.Length i i.Length
|_->printfn "%A does not squeeze <<<%s>>> (length %d)" g n n.Length
isSqueezable "" ' '
isSqueezable "\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln " '-'
isSqueezable "..1111111111111111111111111111111111111111111111111111111111111117777888" '7'
isSqueezable "I never give 'em hell, I just tell the truth, and they think it's hell. " '.'
let fN=isSqueezable " --- Harry S Truman " in fN ' '; fN '-'; fN 'r'
| using System;
using static System.Linq.Enumerable;
public class Program
{
static void Main()
{
SqueezeAndPrint("", ' ');
SqueezeAndPrint("\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln ", '-');
SqueezeAndPrint("..1111111111111111111111111111111111111111111111111111111111111117777888", '7');
SqueezeAndPrint("I never give 'em hell, I just tell the truth, and they think it's hell. ", '.');
string s = " --- Harry S Truman ";
SqueezeAndPrint(s, ' ');
SqueezeAndPrint(s, '-');
SqueezeAndPrint(s, 'r');
}
static void SqueezeAndPrint(string s, char c) {
Console.WriteLine($"squeeze: '{c}'");
Console.WriteLine($"old: {s.Length} «««{s}»»»");
s = Squeeze(s, c);
Console.WriteLine($"new: {s.Length} «««{s}»»»");
}
static string Squeeze(string s, char c) => string.IsNullOrEmpty(s) ? "" :
s[0] + new string(Range(1, s.Length - 1).Where(i => s[i] != c || s[i] != s[i - 1]).Select(i => s[i]).ToArray());
}
|
Write the same code in C++ as shown below in F#. |
let squeeze n i=if String.length n=0 then None else
let fN=let mutable g=n.[0] in (fun n->if n=i && n=g then false else g<-n; true)
let fG=n.[0..0]+System.String(n.[1..].ToCharArray()|>Array.filter fN)
if fG.Length=n.Length then None else Some fG
let isSqueezable n g=match squeeze n g with
Some i->printfn "%A squeezes <<<%s>>> (length %d) to <<<%s>>> (length %d)" g n n.Length i i.Length
|_->printfn "%A does not squeeze <<<%s>>> (length %d)" g n n.Length
isSqueezable "" ' '
isSqueezable "\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln " '-'
isSqueezable "..1111111111111111111111111111111111111111111111111111111111111117777888" '7'
isSqueezable "I never give 'em hell, I just tell the truth, and they think it's hell. " '.'
let fN=isSqueezable " --- Harry S Truman " in fN ' '; fN '-'; fN 'r'
| #include <algorithm>
#include <string>
#include <iostream>
template<typename char_type>
std::basic_string<char_type> squeeze(std::basic_string<char_type> str, char_type ch) {
auto i = std::unique(str.begin(), str.end(),
[ch](char_type a, char_type b) { return a == ch && b == ch; });
str.erase(i, str.end());
return str;
}
void test(const std::string& str, char ch) {
std::cout << "character: '" << ch << "'\n";
std::cout << "original: <<<" << str << ">>>, length: " << str.length() << '\n';
std::string squeezed(squeeze(str, ch));
std::cout << "result: <<<" << squeezed << ">>>, length: " << squeezed.length() << '\n';
std::cout << '\n';
}
int main(int argc, char** argv) {
test("", ' ');
test("\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln ", '-');
test("..1111111111111111111111111111111111111111111111111111111111111117777888", '7');
test("I never give 'em hell, I just tell the truth, and they think it's hell. ", '.');
std::string truman(" --- Harry S Truman ");
test(truman, ' ');
test(truman, '-');
test(truman, 'r');
return 0;
}
|
Rewrite this program in C++ while keeping its functionality equivalent to the F# version. |
let squeeze n i=if String.length n=0 then None else
let fN=let mutable g=n.[0] in (fun n->if n=i && n=g then false else g<-n; true)
let fG=n.[0..0]+System.String(n.[1..].ToCharArray()|>Array.filter fN)
if fG.Length=n.Length then None else Some fG
let isSqueezable n g=match squeeze n g with
Some i->printfn "%A squeezes <<<%s>>> (length %d) to <<<%s>>> (length %d)" g n n.Length i i.Length
|_->printfn "%A does not squeeze <<<%s>>> (length %d)" g n n.Length
isSqueezable "" ' '
isSqueezable "\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln " '-'
isSqueezable "..1111111111111111111111111111111111111111111111111111111111111117777888" '7'
isSqueezable "I never give 'em hell, I just tell the truth, and they think it's hell. " '.'
let fN=isSqueezable " --- Harry S Truman " in fN ' '; fN '-'; fN 'r'
| #include <algorithm>
#include <string>
#include <iostream>
template<typename char_type>
std::basic_string<char_type> squeeze(std::basic_string<char_type> str, char_type ch) {
auto i = std::unique(str.begin(), str.end(),
[ch](char_type a, char_type b) { return a == ch && b == ch; });
str.erase(i, str.end());
return str;
}
void test(const std::string& str, char ch) {
std::cout << "character: '" << ch << "'\n";
std::cout << "original: <<<" << str << ">>>, length: " << str.length() << '\n';
std::string squeezed(squeeze(str, ch));
std::cout << "result: <<<" << squeezed << ">>>, length: " << squeezed.length() << '\n';
std::cout << '\n';
}
int main(int argc, char** argv) {
test("", ' ');
test("\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln ", '-');
test("..1111111111111111111111111111111111111111111111111111111111111117777888", '7');
test("I never give 'em hell, I just tell the truth, and they think it's hell. ", '.');
std::string truman(" --- Harry S Truman ");
test(truman, ' ');
test(truman, '-');
test(truman, 'r');
return 0;
}
|
Port the provided F# code into Java while preserving the original functionality. |
let squeeze n i=if String.length n=0 then None else
let fN=let mutable g=n.[0] in (fun n->if n=i && n=g then false else g<-n; true)
let fG=n.[0..0]+System.String(n.[1..].ToCharArray()|>Array.filter fN)
if fG.Length=n.Length then None else Some fG
let isSqueezable n g=match squeeze n g with
Some i->printfn "%A squeezes <<<%s>>> (length %d) to <<<%s>>> (length %d)" g n n.Length i i.Length
|_->printfn "%A does not squeeze <<<%s>>> (length %d)" g n n.Length
isSqueezable "" ' '
isSqueezable "\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln " '-'
isSqueezable "..1111111111111111111111111111111111111111111111111111111111111117777888" '7'
isSqueezable "I never give 'em hell, I just tell the truth, and they think it's hell. " '.'
let fN=isSqueezable " --- Harry S Truman " in fN ' '; fN '-'; fN 'r'
|
public class StringSqueezable {
public static void main(String[] args) {
String[] testStrings = new String[] {
"",
"\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln ",
"..1111111111111111111111111111111111111111111111111111111111111117777888",
"I never give 'em hell, I just tell the truth, and they think it's hell. ",
" --- Harry S Truman ",
"122333444455555666666777777788888888999999999",
"The better the 4-wheel drive, the further you'll be from help when ya get stuck!",
"headmistressship"};
String[] testChar = new String[] {
" ",
"-",
"7",
".",
" -r",
"5",
"e",
"s"};
for ( int testNum = 0 ; testNum < testStrings.length ; testNum++ ) {
String s = testStrings[testNum];
for ( char c : testChar[testNum].toCharArray() ) {
String result = squeeze(s, c);
System.out.printf("use: '%c'%nold: %2d <<<%s>>>%nnew: %2d <<<%s>>>%n%n", c, s.length(), s, result.length(), result);
}
}
}
private static String squeeze(String in, char include) {
StringBuilder sb = new StringBuilder();
for ( int i = 0 ; i < in.length() ; i++ ) {
if ( i == 0 || in.charAt(i-1) != in.charAt(i) || (in.charAt(i-1) == in.charAt(i) && in.charAt(i) != include)) {
sb.append(in.charAt(i));
}
}
return sb.toString();
}
}
|
Write a version of this F# function in Java with identical behavior. |
let squeeze n i=if String.length n=0 then None else
let fN=let mutable g=n.[0] in (fun n->if n=i && n=g then false else g<-n; true)
let fG=n.[0..0]+System.String(n.[1..].ToCharArray()|>Array.filter fN)
if fG.Length=n.Length then None else Some fG
let isSqueezable n g=match squeeze n g with
Some i->printfn "%A squeezes <<<%s>>> (length %d) to <<<%s>>> (length %d)" g n n.Length i i.Length
|_->printfn "%A does not squeeze <<<%s>>> (length %d)" g n n.Length
isSqueezable "" ' '
isSqueezable "\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln " '-'
isSqueezable "..1111111111111111111111111111111111111111111111111111111111111117777888" '7'
isSqueezable "I never give 'em hell, I just tell the truth, and they think it's hell. " '.'
let fN=isSqueezable " --- Harry S Truman " in fN ' '; fN '-'; fN 'r'
|
public class StringSqueezable {
public static void main(String[] args) {
String[] testStrings = new String[] {
"",
"\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln ",
"..1111111111111111111111111111111111111111111111111111111111111117777888",
"I never give 'em hell, I just tell the truth, and they think it's hell. ",
" --- Harry S Truman ",
"122333444455555666666777777788888888999999999",
"The better the 4-wheel drive, the further you'll be from help when ya get stuck!",
"headmistressship"};
String[] testChar = new String[] {
" ",
"-",
"7",
".",
" -r",
"5",
"e",
"s"};
for ( int testNum = 0 ; testNum < testStrings.length ; testNum++ ) {
String s = testStrings[testNum];
for ( char c : testChar[testNum].toCharArray() ) {
String result = squeeze(s, c);
System.out.printf("use: '%c'%nold: %2d <<<%s>>>%nnew: %2d <<<%s>>>%n%n", c, s.length(), s, result.length(), result);
}
}
}
private static String squeeze(String in, char include) {
StringBuilder sb = new StringBuilder();
for ( int i = 0 ; i < in.length() ; i++ ) {
if ( i == 0 || in.charAt(i-1) != in.charAt(i) || (in.charAt(i-1) == in.charAt(i) && in.charAt(i) != include)) {
sb.append(in.charAt(i));
}
}
return sb.toString();
}
}
|
Translate the given F# code snippet into Python without altering its behavior. |
let squeeze n i=if String.length n=0 then None else
let fN=let mutable g=n.[0] in (fun n->if n=i && n=g then false else g<-n; true)
let fG=n.[0..0]+System.String(n.[1..].ToCharArray()|>Array.filter fN)
if fG.Length=n.Length then None else Some fG
let isSqueezable n g=match squeeze n g with
Some i->printfn "%A squeezes <<<%s>>> (length %d) to <<<%s>>> (length %d)" g n n.Length i i.Length
|_->printfn "%A does not squeeze <<<%s>>> (length %d)" g n n.Length
isSqueezable "" ' '
isSqueezable "\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln " '-'
isSqueezable "..1111111111111111111111111111111111111111111111111111111111111117777888" '7'
isSqueezable "I never give 'em hell, I just tell the truth, and they think it's hell. " '.'
let fN=isSqueezable " --- Harry S Truman " in fN ' '; fN '-'; fN 'r'
| from itertools import groupby
def squeezer(s, txt):
return ''.join(item if item == s else ''.join(grp)
for item, grp in groupby(txt))
if __name__ == '__main__':
strings = [
"",
'"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln ',
"..1111111111111111111111111111111111111111111111111111111111111117777888",
"I never give 'em hell, I just tell the truth, and they think it's hell. ",
" --- Harry S Truman ",
"The better the 4-wheel drive, the further you'll be from help when ya get stuck!",
"headmistressship",
"aardvark",
"😍😀🙌💃😍😍😍🙌",
]
squeezers = ' ,-,7,., -r,e,s,a,😍'.split(',')
for txt, chars in zip(strings, squeezers):
this = "Original"
print(f"\n{this:14} Size: {len(txt)} «««{txt}»»»" )
for ch in chars:
this = f"Squeezer '{ch}'"
sqz = squeezer(ch, txt)
print(f"{this:>14} Size: {len(sqz)} «««{sqz}»»»" )
|
Generate a Python translation of this F# snippet without changing its computational steps. |
let squeeze n i=if String.length n=0 then None else
let fN=let mutable g=n.[0] in (fun n->if n=i && n=g then false else g<-n; true)
let fG=n.[0..0]+System.String(n.[1..].ToCharArray()|>Array.filter fN)
if fG.Length=n.Length then None else Some fG
let isSqueezable n g=match squeeze n g with
Some i->printfn "%A squeezes <<<%s>>> (length %d) to <<<%s>>> (length %d)" g n n.Length i i.Length
|_->printfn "%A does not squeeze <<<%s>>> (length %d)" g n n.Length
isSqueezable "" ' '
isSqueezable "\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln " '-'
isSqueezable "..1111111111111111111111111111111111111111111111111111111111111117777888" '7'
isSqueezable "I never give 'em hell, I just tell the truth, and they think it's hell. " '.'
let fN=isSqueezable " --- Harry S Truman " in fN ' '; fN '-'; fN 'r'
| from itertools import groupby
def squeezer(s, txt):
return ''.join(item if item == s else ''.join(grp)
for item, grp in groupby(txt))
if __name__ == '__main__':
strings = [
"",
'"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln ',
"..1111111111111111111111111111111111111111111111111111111111111117777888",
"I never give 'em hell, I just tell the truth, and they think it's hell. ",
" --- Harry S Truman ",
"The better the 4-wheel drive, the further you'll be from help when ya get stuck!",
"headmistressship",
"aardvark",
"😍😀🙌💃😍😍😍🙌",
]
squeezers = ' ,-,7,., -r,e,s,a,😍'.split(',')
for txt, chars in zip(strings, squeezers):
this = "Original"
print(f"\n{this:14} Size: {len(txt)} «««{txt}»»»" )
for ch in chars:
this = f"Squeezer '{ch}'"
sqz = squeezer(ch, txt)
print(f"{this:>14} Size: {len(sqz)} «««{sqz}»»»" )
|
Convert the following code from F# to VB, ensuring the logic remains intact. |
let squeeze n i=if String.length n=0 then None else
let fN=let mutable g=n.[0] in (fun n->if n=i && n=g then false else g<-n; true)
let fG=n.[0..0]+System.String(n.[1..].ToCharArray()|>Array.filter fN)
if fG.Length=n.Length then None else Some fG
let isSqueezable n g=match squeeze n g with
Some i->printfn "%A squeezes <<<%s>>> (length %d) to <<<%s>>> (length %d)" g n n.Length i i.Length
|_->printfn "%A does not squeeze <<<%s>>> (length %d)" g n n.Length
isSqueezable "" ' '
isSqueezable "\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln " '-'
isSqueezable "..1111111111111111111111111111111111111111111111111111111111111117777888" '7'
isSqueezable "I never give 'em hell, I just tell the truth, and they think it's hell. " '.'
let fN=isSqueezable " --- Harry S Truman " in fN ' '; fN '-'; fN 'r'
| Imports System.Linq.Enumerable
Module Module1
Function Squeeze(s As String, c As Char) As String
If String.IsNullOrEmpty(s) Then
Return ""
End If
Return s(0) + New String(Range(1, s.Length - 1).Where(Function(i) s(i) <> c OrElse s(i) <> s(i - 1)).Select(Function(i) s(i)).ToArray())
End Function
Sub SqueezeAndPrint(s As String, c As Char)
Console.WriteLine("squeeze:
Console.WriteLine("old: {0} «««{1}»»»", s.Length, s)
s = Squeeze(s, c)
Console.WriteLine("new: {0} «««{1}»»»", s.Length, s)
End Sub
Sub Main()
Const QUOTE = """"
SqueezeAndPrint("", " ")
SqueezeAndPrint(QUOTE & "If I were two-faced, would I be wearing this one?" & QUOTE & " --- Abraham Lincoln ", "-")
SqueezeAndPrint("..1111111111111111111111111111111111111111111111111111111111111117777888", "7")
SqueezeAndPrint("I never give
Dim s = " --- Harry S Truman "
SqueezeAndPrint(s, " ")
SqueezeAndPrint(s, "-")
SqueezeAndPrint(s, "r")
End Sub
End Module
|
Rewrite this program in VB while keeping its functionality equivalent to the F# version. |
let squeeze n i=if String.length n=0 then None else
let fN=let mutable g=n.[0] in (fun n->if n=i && n=g then false else g<-n; true)
let fG=n.[0..0]+System.String(n.[1..].ToCharArray()|>Array.filter fN)
if fG.Length=n.Length then None else Some fG
let isSqueezable n g=match squeeze n g with
Some i->printfn "%A squeezes <<<%s>>> (length %d) to <<<%s>>> (length %d)" g n n.Length i i.Length
|_->printfn "%A does not squeeze <<<%s>>> (length %d)" g n n.Length
isSqueezable "" ' '
isSqueezable "\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln " '-'
isSqueezable "..1111111111111111111111111111111111111111111111111111111111111117777888" '7'
isSqueezable "I never give 'em hell, I just tell the truth, and they think it's hell. " '.'
let fN=isSqueezable " --- Harry S Truman " in fN ' '; fN '-'; fN 'r'
| Imports System.Linq.Enumerable
Module Module1
Function Squeeze(s As String, c As Char) As String
If String.IsNullOrEmpty(s) Then
Return ""
End If
Return s(0) + New String(Range(1, s.Length - 1).Where(Function(i) s(i) <> c OrElse s(i) <> s(i - 1)).Select(Function(i) s(i)).ToArray())
End Function
Sub SqueezeAndPrint(s As String, c As Char)
Console.WriteLine("squeeze:
Console.WriteLine("old: {0} «««{1}»»»", s.Length, s)
s = Squeeze(s, c)
Console.WriteLine("new: {0} «««{1}»»»", s.Length, s)
End Sub
Sub Main()
Const QUOTE = """"
SqueezeAndPrint("", " ")
SqueezeAndPrint(QUOTE & "If I were two-faced, would I be wearing this one?" & QUOTE & " --- Abraham Lincoln ", "-")
SqueezeAndPrint("..1111111111111111111111111111111111111111111111111111111111111117777888", "7")
SqueezeAndPrint("I never give
Dim s = " --- Harry S Truman "
SqueezeAndPrint(s, " ")
SqueezeAndPrint(s, "-")
SqueezeAndPrint(s, "r")
End Sub
End Module
|
Generate a Go translation of this F# snippet without changing its computational steps. |
let squeeze n i=if String.length n=0 then None else
let fN=let mutable g=n.[0] in (fun n->if n=i && n=g then false else g<-n; true)
let fG=n.[0..0]+System.String(n.[1..].ToCharArray()|>Array.filter fN)
if fG.Length=n.Length then None else Some fG
let isSqueezable n g=match squeeze n g with
Some i->printfn "%A squeezes <<<%s>>> (length %d) to <<<%s>>> (length %d)" g n n.Length i i.Length
|_->printfn "%A does not squeeze <<<%s>>> (length %d)" g n n.Length
isSqueezable "" ' '
isSqueezable "\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln " '-'
isSqueezable "..1111111111111111111111111111111111111111111111111111111111111117777888" '7'
isSqueezable "I never give 'em hell, I just tell the truth, and they think it's hell. " '.'
let fN=isSqueezable " --- Harry S Truman " in fN ' '; fN '-'; fN 'r'
| package main
import "fmt"
func squeeze(s string, c rune) (string, int, int) {
r := []rune(s)
le, del := len(r), 0
for i := le - 2; i >= 0; i-- {
if r[i] == c && r[i] == r[i+1] {
copy(r[i:], r[i+1:])
del++
}
}
if del == 0 {
return s, le, le
}
r = r[:le-del]
return string(r), le, len(r)
}
func main() {
strings := []string{
"",
`"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln `,
"..1111111111111111111111111111111111111111111111111111111111111117777888",
"I never give 'em hell, I just tell the truth, and they think it's hell. ",
" --- Harry S Truman ",
"The better the 4-wheel drive, the further you'll be from help when ya get stuck!",
"headmistressship",
"aardvark",
"😍😀🙌💃😍😍😍🙌",
}
chars := [][]rune{{' '}, {'-'}, {'7'}, {'.'}, {' ', '-', 'r'}, {'e'}, {'s'}, {'a'}, {'😍'}}
for i, s := range strings {
for _, c := range chars[i] {
ss, olen, slen := squeeze(s, c)
fmt.Printf("specified character = %q\n", c)
fmt.Printf("original : length = %2d, string = «««%s»»»\n", olen, s)
fmt.Printf("squeezed : length = %2d, string = «««%s»»»\n\n", slen, ss)
}
}
}
|
Transform the following F# implementation into Go, maintaining the same output and logic. |
let squeeze n i=if String.length n=0 then None else
let fN=let mutable g=n.[0] in (fun n->if n=i && n=g then false else g<-n; true)
let fG=n.[0..0]+System.String(n.[1..].ToCharArray()|>Array.filter fN)
if fG.Length=n.Length then None else Some fG
let isSqueezable n g=match squeeze n g with
Some i->printfn "%A squeezes <<<%s>>> (length %d) to <<<%s>>> (length %d)" g n n.Length i i.Length
|_->printfn "%A does not squeeze <<<%s>>> (length %d)" g n n.Length
isSqueezable "" ' '
isSqueezable "\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln " '-'
isSqueezable "..1111111111111111111111111111111111111111111111111111111111111117777888" '7'
isSqueezable "I never give 'em hell, I just tell the truth, and they think it's hell. " '.'
let fN=isSqueezable " --- Harry S Truman " in fN ' '; fN '-'; fN 'r'
| package main
import "fmt"
func squeeze(s string, c rune) (string, int, int) {
r := []rune(s)
le, del := len(r), 0
for i := le - 2; i >= 0; i-- {
if r[i] == c && r[i] == r[i+1] {
copy(r[i:], r[i+1:])
del++
}
}
if del == 0 {
return s, le, le
}
r = r[:le-del]
return string(r), le, len(r)
}
func main() {
strings := []string{
"",
`"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln `,
"..1111111111111111111111111111111111111111111111111111111111111117777888",
"I never give 'em hell, I just tell the truth, and they think it's hell. ",
" --- Harry S Truman ",
"The better the 4-wheel drive, the further you'll be from help when ya get stuck!",
"headmistressship",
"aardvark",
"😍😀🙌💃😍😍😍🙌",
}
chars := [][]rune{{' '}, {'-'}, {'7'}, {'.'}, {' ', '-', 'r'}, {'e'}, {'s'}, {'a'}, {'😍'}}
for i, s := range strings {
for _, c := range chars[i] {
ss, olen, slen := squeeze(s, c)
fmt.Printf("specified character = %q\n", c)
fmt.Printf("original : length = %2d, string = «««%s»»»\n", olen, s)
fmt.Printf("squeezed : length = %2d, string = «««%s»»»\n\n", slen, ss)
}
}
}
|
Convert this Factor snippet to C and keep its semantics consistent. | USING: formatting fry io kernel math sbufs sequences strings ;
IN: rosetta-code.squeeze
: (squeeze) ( str c -- new-str )
[ unclip-slice 1string >sbuf ] dip
'[ over last over [ _ = ] both? [ drop ] [ suffix
reduce >string ;
: squeeze ( str c -- new-str )
over empty? [ 2drop "" ] [ (squeeze) ] if ;
: .str ( str -- ) dup length "«««%s»»» (length %d)\n" printf ;
: show-squeeze ( str c -- )
dup "Specified character: '%c'\n" printf
[ "Before squeeze: " write drop .str ]
[ "After squeeze: " write squeeze .str ] 2bi nl ;
: squeeze-demo ( -- )
{
""
"\"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. "
} "\0-7." [ show-squeeze ] 2each
" --- Harry S Truman "
[ CHAR: space ] [ CHAR: - ] [ CHAR: r ] tri
[ show-squeeze ] 2tri@ ;
MAIN: squeeze-demo
| #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 Factor to C. | USING: formatting fry io kernel math sbufs sequences strings ;
IN: rosetta-code.squeeze
: (squeeze) ( str c -- new-str )
[ unclip-slice 1string >sbuf ] dip
'[ over last over [ _ = ] both? [ drop ] [ suffix
reduce >string ;
: squeeze ( str c -- new-str )
over empty? [ 2drop "" ] [ (squeeze) ] if ;
: .str ( str -- ) dup length "«««%s»»» (length %d)\n" printf ;
: show-squeeze ( str c -- )
dup "Specified character: '%c'\n" printf
[ "Before squeeze: " write drop .str ]
[ "After squeeze: " write squeeze .str ] 2bi nl ;
: squeeze-demo ( -- )
{
""
"\"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. "
} "\0-7." [ show-squeeze ] 2each
" --- Harry S Truman "
[ CHAR: space ] [ CHAR: - ] [ CHAR: r ] tri
[ show-squeeze ] 2tri@ ;
MAIN: squeeze-demo
| #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 Factor code into C# while preserving the original functionality. | USING: formatting fry io kernel math sbufs sequences strings ;
IN: rosetta-code.squeeze
: (squeeze) ( str c -- new-str )
[ unclip-slice 1string >sbuf ] dip
'[ over last over [ _ = ] both? [ drop ] [ suffix
reduce >string ;
: squeeze ( str c -- new-str )
over empty? [ 2drop "" ] [ (squeeze) ] if ;
: .str ( str -- ) dup length "«««%s»»» (length %d)\n" printf ;
: show-squeeze ( str c -- )
dup "Specified character: '%c'\n" printf
[ "Before squeeze: " write drop .str ]
[ "After squeeze: " write squeeze .str ] 2bi nl ;
: squeeze-demo ( -- )
{
""
"\"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. "
} "\0-7." [ show-squeeze ] 2each
" --- Harry S Truman "
[ CHAR: space ] [ CHAR: - ] [ CHAR: r ] tri
[ show-squeeze ] 2tri@ ;
MAIN: squeeze-demo
| 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#. | USING: formatting fry io kernel math sbufs sequences strings ;
IN: rosetta-code.squeeze
: (squeeze) ( str c -- new-str )
[ unclip-slice 1string >sbuf ] dip
'[ over last over [ _ = ] both? [ drop ] [ suffix
reduce >string ;
: squeeze ( str c -- new-str )
over empty? [ 2drop "" ] [ (squeeze) ] if ;
: .str ( str -- ) dup length "«««%s»»» (length %d)\n" printf ;
: show-squeeze ( str c -- )
dup "Specified character: '%c'\n" printf
[ "Before squeeze: " write drop .str ]
[ "After squeeze: " write squeeze .str ] 2bi nl ;
: squeeze-demo ( -- )
{
""
"\"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. "
} "\0-7." [ show-squeeze ] 2each
" --- Harry S Truman "
[ CHAR: space ] [ CHAR: - ] [ CHAR: r ] tri
[ show-squeeze ] 2tri@ ;
MAIN: squeeze-demo
| 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());
}
|
Generate a C++ translation of this Factor snippet without changing its computational steps. | USING: formatting fry io kernel math sbufs sequences strings ;
IN: rosetta-code.squeeze
: (squeeze) ( str c -- new-str )
[ unclip-slice 1string >sbuf ] dip
'[ over last over [ _ = ] both? [ drop ] [ suffix
reduce >string ;
: squeeze ( str c -- new-str )
over empty? [ 2drop "" ] [ (squeeze) ] if ;
: .str ( str -- ) dup length "«««%s»»» (length %d)\n" printf ;
: show-squeeze ( str c -- )
dup "Specified character: '%c'\n" printf
[ "Before squeeze: " write drop .str ]
[ "After squeeze: " write squeeze .str ] 2bi nl ;
: squeeze-demo ( -- )
{
""
"\"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. "
} "\0-7." [ show-squeeze ] 2each
" --- Harry S Truman "
[ CHAR: space ] [ CHAR: - ] [ CHAR: r ] tri
[ show-squeeze ] 2tri@ ;
MAIN: squeeze-demo
| #include <algorithm>
#include <string>
#include <iostream>
template<typename char_type>
std::basic_string<char_type> squeeze(std::basic_string<char_type> str, char_type ch) {
auto i = std::unique(str.begin(), str.end(),
[ch](char_type a, char_type b) { return a == ch && b == ch; });
str.erase(i, str.end());
return str;
}
void test(const std::string& str, char ch) {
std::cout << "character: '" << ch << "'\n";
std::cout << "original: <<<" << str << ">>>, length: " << str.length() << '\n';
std::string squeezed(squeeze(str, ch));
std::cout << "result: <<<" << squeezed << ">>>, length: " << squeezed.length() << '\n';
std::cout << '\n';
}
int main(int argc, char** argv) {
test("", ' ');
test("\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln ", '-');
test("..1111111111111111111111111111111111111111111111111111111111111117777888", '7');
test("I never give 'em hell, I just tell the truth, and they think it's hell. ", '.');
std::string truman(" --- Harry S Truman ");
test(truman, ' ');
test(truman, '-');
test(truman, 'r');
return 0;
}
|
Produce a functionally identical C++ code for the snippet given in Factor. | USING: formatting fry io kernel math sbufs sequences strings ;
IN: rosetta-code.squeeze
: (squeeze) ( str c -- new-str )
[ unclip-slice 1string >sbuf ] dip
'[ over last over [ _ = ] both? [ drop ] [ suffix
reduce >string ;
: squeeze ( str c -- new-str )
over empty? [ 2drop "" ] [ (squeeze) ] if ;
: .str ( str -- ) dup length "«««%s»»» (length %d)\n" printf ;
: show-squeeze ( str c -- )
dup "Specified character: '%c'\n" printf
[ "Before squeeze: " write drop .str ]
[ "After squeeze: " write squeeze .str ] 2bi nl ;
: squeeze-demo ( -- )
{
""
"\"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. "
} "\0-7." [ show-squeeze ] 2each
" --- Harry S Truman "
[ CHAR: space ] [ CHAR: - ] [ CHAR: r ] tri
[ show-squeeze ] 2tri@ ;
MAIN: squeeze-demo
| #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 Factor block to Java, preserving its control flow and logic. | USING: formatting fry io kernel math sbufs sequences strings ;
IN: rosetta-code.squeeze
: (squeeze) ( str c -- new-str )
[ unclip-slice 1string >sbuf ] dip
'[ over last over [ _ = ] both? [ drop ] [ suffix
reduce >string ;
: squeeze ( str c -- new-str )
over empty? [ 2drop "" ] [ (squeeze) ] if ;
: .str ( str -- ) dup length "«««%s»»» (length %d)\n" printf ;
: show-squeeze ( str c -- )
dup "Specified character: '%c'\n" printf
[ "Before squeeze: " write drop .str ]
[ "After squeeze: " write squeeze .str ] 2bi nl ;
: squeeze-demo ( -- )
{
""
"\"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. "
} "\0-7." [ show-squeeze ] 2each
" --- Harry S Truman "
[ CHAR: space ] [ CHAR: - ] [ CHAR: r ] tri
[ show-squeeze ] 2tri@ ;
MAIN: squeeze-demo
|
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 Factor implementation into Java, maintaining the same output and logic. | USING: formatting fry io kernel math sbufs sequences strings ;
IN: rosetta-code.squeeze
: (squeeze) ( str c -- new-str )
[ unclip-slice 1string >sbuf ] dip
'[ over last over [ _ = ] both? [ drop ] [ suffix
reduce >string ;
: squeeze ( str c -- new-str )
over empty? [ 2drop "" ] [ (squeeze) ] if ;
: .str ( str -- ) dup length "«««%s»»» (length %d)\n" printf ;
: show-squeeze ( str c -- )
dup "Specified character: '%c'\n" printf
[ "Before squeeze: " write drop .str ]
[ "After squeeze: " write squeeze .str ] 2bi nl ;
: squeeze-demo ( -- )
{
""
"\"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. "
} "\0-7." [ show-squeeze ] 2each
" --- Harry S Truman "
[ CHAR: space ] [ CHAR: - ] [ CHAR: r ] tri
[ show-squeeze ] 2tri@ ;
MAIN: squeeze-demo
|
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 Factor block to Python, preserving its control flow and logic. | USING: formatting fry io kernel math sbufs sequences strings ;
IN: rosetta-code.squeeze
: (squeeze) ( str c -- new-str )
[ unclip-slice 1string >sbuf ] dip
'[ over last over [ _ = ] both? [ drop ] [ suffix
reduce >string ;
: squeeze ( str c -- new-str )
over empty? [ 2drop "" ] [ (squeeze) ] if ;
: .str ( str -- ) dup length "«««%s»»» (length %d)\n" printf ;
: show-squeeze ( str c -- )
dup "Specified character: '%c'\n" printf
[ "Before squeeze: " write drop .str ]
[ "After squeeze: " write squeeze .str ] 2bi nl ;
: squeeze-demo ( -- )
{
""
"\"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. "
} "\0-7." [ show-squeeze ] 2each
" --- Harry S Truman "
[ CHAR: space ] [ CHAR: - ] [ CHAR: r ] tri
[ show-squeeze ] 2tri@ ;
MAIN: squeeze-demo
| 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 the given Factor code snippet into Python without altering its behavior. | USING: formatting fry io kernel math sbufs sequences strings ;
IN: rosetta-code.squeeze
: (squeeze) ( str c -- new-str )
[ unclip-slice 1string >sbuf ] dip
'[ over last over [ _ = ] both? [ drop ] [ suffix
reduce >string ;
: squeeze ( str c -- new-str )
over empty? [ 2drop "" ] [ (squeeze) ] if ;
: .str ( str -- ) dup length "«««%s»»» (length %d)\n" printf ;
: show-squeeze ( str c -- )
dup "Specified character: '%c'\n" printf
[ "Before squeeze: " write drop .str ]
[ "After squeeze: " write squeeze .str ] 2bi nl ;
: squeeze-demo ( -- )
{
""
"\"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. "
} "\0-7." [ show-squeeze ] 2each
" --- Harry S Truman "
[ CHAR: space ] [ CHAR: - ] [ CHAR: r ] tri
[ show-squeeze ] 2tri@ ;
MAIN: squeeze-demo
| 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}»»»" )
|
Can you help me rewrite this code in VB instead of Factor, keeping it the same logically? | USING: formatting fry io kernel math sbufs sequences strings ;
IN: rosetta-code.squeeze
: (squeeze) ( str c -- new-str )
[ unclip-slice 1string >sbuf ] dip
'[ over last over [ _ = ] both? [ drop ] [ suffix
reduce >string ;
: squeeze ( str c -- new-str )
over empty? [ 2drop "" ] [ (squeeze) ] if ;
: .str ( str -- ) dup length "«««%s»»» (length %d)\n" printf ;
: show-squeeze ( str c -- )
dup "Specified character: '%c'\n" printf
[ "Before squeeze: " write drop .str ]
[ "After squeeze: " write squeeze .str ] 2bi nl ;
: squeeze-demo ( -- )
{
""
"\"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. "
} "\0-7." [ show-squeeze ] 2each
" --- Harry S Truman "
[ CHAR: space ] [ CHAR: - ] [ CHAR: r ] tri
[ show-squeeze ] 2tri@ ;
MAIN: squeeze-demo
| 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 an equivalent VB version of this Factor code. | USING: formatting fry io kernel math sbufs sequences strings ;
IN: rosetta-code.squeeze
: (squeeze) ( str c -- new-str )
[ unclip-slice 1string >sbuf ] dip
'[ over last over [ _ = ] both? [ drop ] [ suffix
reduce >string ;
: squeeze ( str c -- new-str )
over empty? [ 2drop "" ] [ (squeeze) ] if ;
: .str ( str -- ) dup length "«««%s»»» (length %d)\n" printf ;
: show-squeeze ( str c -- )
dup "Specified character: '%c'\n" printf
[ "Before squeeze: " write drop .str ]
[ "After squeeze: " write squeeze .str ] 2bi nl ;
: squeeze-demo ( -- )
{
""
"\"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. "
} "\0-7." [ show-squeeze ] 2each
" --- Harry S Truman "
[ CHAR: space ] [ CHAR: - ] [ CHAR: r ] tri
[ show-squeeze ] 2tri@ ;
MAIN: squeeze-demo
| Imports System.Linq.Enumerable
Module Module1
Function Squeeze(s As String, c As Char) As String
If String.IsNullOrEmpty(s) Then
Return ""
End If
Return s(0) + New String(Range(1, s.Length - 1).Where(Function(i) s(i) <> c OrElse s(i) <> s(i - 1)).Select(Function(i) s(i)).ToArray())
End Function
Sub SqueezeAndPrint(s As String, c As Char)
Console.WriteLine("squeeze:
Console.WriteLine("old: {0} «««{1}»»»", s.Length, s)
s = Squeeze(s, c)
Console.WriteLine("new: {0} «««{1}»»»", s.Length, s)
End Sub
Sub Main()
Const QUOTE = """"
SqueezeAndPrint("", " ")
SqueezeAndPrint(QUOTE & "If I were two-faced, would I be wearing this one?" & QUOTE & " --- Abraham Lincoln ", "-")
SqueezeAndPrint("..1111111111111111111111111111111111111111111111111111111111111117777888", "7")
SqueezeAndPrint("I never give
Dim s = " --- Harry S Truman "
SqueezeAndPrint(s, " ")
SqueezeAndPrint(s, "-")
SqueezeAndPrint(s, "r")
End Sub
End Module
|
Rewrite the snippet below in Go so it works the same as the original Factor code. | USING: formatting fry io kernel math sbufs sequences strings ;
IN: rosetta-code.squeeze
: (squeeze) ( str c -- new-str )
[ unclip-slice 1string >sbuf ] dip
'[ over last over [ _ = ] both? [ drop ] [ suffix
reduce >string ;
: squeeze ( str c -- new-str )
over empty? [ 2drop "" ] [ (squeeze) ] if ;
: .str ( str -- ) dup length "«««%s»»» (length %d)\n" printf ;
: show-squeeze ( str c -- )
dup "Specified character: '%c'\n" printf
[ "Before squeeze: " write drop .str ]
[ "After squeeze: " write squeeze .str ] 2bi nl ;
: squeeze-demo ( -- )
{
""
"\"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. "
} "\0-7." [ show-squeeze ] 2each
" --- Harry S Truman "
[ CHAR: space ] [ CHAR: - ] [ CHAR: r ] tri
[ show-squeeze ] 2tri@ ;
MAIN: squeeze-demo
| 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 Go code for the snippet given in Factor. | USING: formatting fry io kernel math sbufs sequences strings ;
IN: rosetta-code.squeeze
: (squeeze) ( str c -- new-str )
[ unclip-slice 1string >sbuf ] dip
'[ over last over [ _ = ] both? [ drop ] [ suffix
reduce >string ;
: squeeze ( str c -- new-str )
over empty? [ 2drop "" ] [ (squeeze) ] if ;
: .str ( str -- ) dup length "«««%s»»» (length %d)\n" printf ;
: show-squeeze ( str c -- )
dup "Specified character: '%c'\n" printf
[ "Before squeeze: " write drop .str ]
[ "After squeeze: " write squeeze .str ] 2bi nl ;
: squeeze-demo ( -- )
{
""
"\"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. "
} "\0-7." [ show-squeeze ] 2each
" --- Harry S Truman "
[ CHAR: space ] [ CHAR: - ] [ CHAR: r ] tri
[ show-squeeze ] 2tri@ ;
MAIN: squeeze-demo
| package main
import "fmt"
func squeeze(s string, c rune) (string, int, int) {
r := []rune(s)
le, del := len(r), 0
for i := le - 2; i >= 0; i-- {
if r[i] == c && r[i] == r[i+1] {
copy(r[i:], r[i+1:])
del++
}
}
if del == 0 {
return s, le, le
}
r = r[:le-del]
return string(r), le, len(r)
}
func main() {
strings := []string{
"",
`"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln `,
"..1111111111111111111111111111111111111111111111111111111111111117777888",
"I never give 'em hell, I just tell the truth, and they think it's hell. ",
" --- Harry S Truman ",
"The better the 4-wheel drive, the further you'll be from help when ya get stuck!",
"headmistressship",
"aardvark",
"😍😀🙌💃😍😍😍🙌",
}
chars := [][]rune{{' '}, {'-'}, {'7'}, {'.'}, {' ', '-', 'r'}, {'e'}, {'s'}, {'a'}, {'😍'}}
for i, s := range strings {
for _, c := range chars[i] {
ss, olen, slen := squeeze(s, c)
fmt.Printf("specified character = %q\n", c)
fmt.Printf("original : length = %2d, string = «««%s»»»\n", olen, s)
fmt.Printf("squeezed : length = %2d, string = «««%s»»»\n\n", slen, ss)
}
}
}
|
Write the same algorithm in C# as shown in this Fortran implementation. | program main
implicit none
character(len=:),allocatable :: strings(:)
strings=[ character(len=72) :: &
'', &
'"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln', &
'..1111111111111111111111111111111111111111111111111111111111111117777888', &
'I never give ''em hell, I just tell the truth, and they think it''s hell.',&
' --- Harry S Truman' &
]
call printme( trim(strings(1)), ' ' )
call printme( strings(2:4), ['-','7','.'] )
call printme( strings(5), [' ','-','r'] )
contains
impure elemental subroutine printme(str,chr)
character(len=*),intent(in) :: str
character(len=1),intent(in) :: chr
character(len=:),allocatable :: answer
write(*,'(a)')repeat('=',9)
write(*,'("IN: <<<",g0,">>>")')str
answer=compact(str,chr)
write(*,'("OUT: <<<",g0,">>>")')answer
write(*,'("LENS: ",*(g0,1x))')"from",len(str),"to",len(answer),"for a change of",len(str)-len(answer)
write(*,'("CHAR: ",g0)')chr
end subroutine printme
elemental function compact(str,charp) result (outstr)
character(len=*),intent(in) :: str
character(len=1),intent(in) :: charp
character(len=:),allocatable :: outstr
character(len=1) :: ch, last_one
integer :: i, pio
outstr=repeat(' ',len(str))
if(len(outstr)==0)return
last_one=str(1:1)
outstr(1:1)=last_one
pio=1
do i=2,len(str)
ch=str(i:i)
pio=pio+merge(0,1, ch.eq.last_one.and.ch.eq.charp)
outstr(pio:pio)=ch
last_one=ch
enddo
outstr=outstr(:pio)
end function compact
end program main
}
| 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 Fortran code into C# while preserving the original functionality. | program main
implicit none
character(len=:),allocatable :: strings(:)
strings=[ character(len=72) :: &
'', &
'"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln', &
'..1111111111111111111111111111111111111111111111111111111111111117777888', &
'I never give ''em hell, I just tell the truth, and they think it''s hell.',&
' --- Harry S Truman' &
]
call printme( trim(strings(1)), ' ' )
call printme( strings(2:4), ['-','7','.'] )
call printme( strings(5), [' ','-','r'] )
contains
impure elemental subroutine printme(str,chr)
character(len=*),intent(in) :: str
character(len=1),intent(in) :: chr
character(len=:),allocatable :: answer
write(*,'(a)')repeat('=',9)
write(*,'("IN: <<<",g0,">>>")')str
answer=compact(str,chr)
write(*,'("OUT: <<<",g0,">>>")')answer
write(*,'("LENS: ",*(g0,1x))')"from",len(str),"to",len(answer),"for a change of",len(str)-len(answer)
write(*,'("CHAR: ",g0)')chr
end subroutine printme
elemental function compact(str,charp) result (outstr)
character(len=*),intent(in) :: str
character(len=1),intent(in) :: charp
character(len=:),allocatable :: outstr
character(len=1) :: ch, last_one
integer :: i, pio
outstr=repeat(' ',len(str))
if(len(outstr)==0)return
last_one=str(1:1)
outstr(1:1)=last_one
pio=1
do i=2,len(str)
ch=str(i:i)
pio=pio+merge(0,1, ch.eq.last_one.and.ch.eq.charp)
outstr(pio:pio)=ch
last_one=ch
enddo
outstr=outstr(:pio)
end function compact
end program main
}
| using System;
using static System.Linq.Enumerable;
public class Program
{
static void Main()
{
SqueezeAndPrint("", ' ');
SqueezeAndPrint("\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln ", '-');
SqueezeAndPrint("..1111111111111111111111111111111111111111111111111111111111111117777888", '7');
SqueezeAndPrint("I never give 'em hell, I just tell the truth, and they think it's hell. ", '.');
string s = " --- Harry S Truman ";
SqueezeAndPrint(s, ' ');
SqueezeAndPrint(s, '-');
SqueezeAndPrint(s, 'r');
}
static void SqueezeAndPrint(string s, char c) {
Console.WriteLine($"squeeze: '{c}'");
Console.WriteLine($"old: {s.Length} «««{s}»»»");
s = Squeeze(s, c);
Console.WriteLine($"new: {s.Length} «««{s}»»»");
}
static string Squeeze(string s, char c) => string.IsNullOrEmpty(s) ? "" :
s[0] + new string(Range(1, s.Length - 1).Where(i => s[i] != c || s[i] != s[i - 1]).Select(i => s[i]).ToArray());
}
|
Maintain the same structure and functionality when rewriting this code in C++. | program main
implicit none
character(len=:),allocatable :: strings(:)
strings=[ character(len=72) :: &
'', &
'"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln', &
'..1111111111111111111111111111111111111111111111111111111111111117777888', &
'I never give ''em hell, I just tell the truth, and they think it''s hell.',&
' --- Harry S Truman' &
]
call printme( trim(strings(1)), ' ' )
call printme( strings(2:4), ['-','7','.'] )
call printme( strings(5), [' ','-','r'] )
contains
impure elemental subroutine printme(str,chr)
character(len=*),intent(in) :: str
character(len=1),intent(in) :: chr
character(len=:),allocatable :: answer
write(*,'(a)')repeat('=',9)
write(*,'("IN: <<<",g0,">>>")')str
answer=compact(str,chr)
write(*,'("OUT: <<<",g0,">>>")')answer
write(*,'("LENS: ",*(g0,1x))')"from",len(str),"to",len(answer),"for a change of",len(str)-len(answer)
write(*,'("CHAR: ",g0)')chr
end subroutine printme
elemental function compact(str,charp) result (outstr)
character(len=*),intent(in) :: str
character(len=1),intent(in) :: charp
character(len=:),allocatable :: outstr
character(len=1) :: ch, last_one
integer :: i, pio
outstr=repeat(' ',len(str))
if(len(outstr)==0)return
last_one=str(1:1)
outstr(1:1)=last_one
pio=1
do i=2,len(str)
ch=str(i:i)
pio=pio+merge(0,1, ch.eq.last_one.and.ch.eq.charp)
outstr(pio:pio)=ch
last_one=ch
enddo
outstr=outstr(:pio)
end function compact
end program main
}
| #include <algorithm>
#include <string>
#include <iostream>
template<typename char_type>
std::basic_string<char_type> squeeze(std::basic_string<char_type> str, char_type ch) {
auto i = std::unique(str.begin(), str.end(),
[ch](char_type a, char_type b) { return a == ch && b == ch; });
str.erase(i, str.end());
return str;
}
void test(const std::string& str, char ch) {
std::cout << "character: '" << ch << "'\n";
std::cout << "original: <<<" << str << ">>>, length: " << str.length() << '\n';
std::string squeezed(squeeze(str, ch));
std::cout << "result: <<<" << squeezed << ">>>, length: " << squeezed.length() << '\n';
std::cout << '\n';
}
int main(int argc, char** argv) {
test("", ' ');
test("\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln ", '-');
test("..1111111111111111111111111111111111111111111111111111111111111117777888", '7');
test("I never give 'em hell, I just tell the truth, and they think it's hell. ", '.');
std::string truman(" --- Harry S Truman ");
test(truman, ' ');
test(truman, '-');
test(truman, 'r');
return 0;
}
|
Write the same algorithm in C++ as shown in this Fortran implementation. | program main
implicit none
character(len=:),allocatable :: strings(:)
strings=[ character(len=72) :: &
'', &
'"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln', &
'..1111111111111111111111111111111111111111111111111111111111111117777888', &
'I never give ''em hell, I just tell the truth, and they think it''s hell.',&
' --- Harry S Truman' &
]
call printme( trim(strings(1)), ' ' )
call printme( strings(2:4), ['-','7','.'] )
call printme( strings(5), [' ','-','r'] )
contains
impure elemental subroutine printme(str,chr)
character(len=*),intent(in) :: str
character(len=1),intent(in) :: chr
character(len=:),allocatable :: answer
write(*,'(a)')repeat('=',9)
write(*,'("IN: <<<",g0,">>>")')str
answer=compact(str,chr)
write(*,'("OUT: <<<",g0,">>>")')answer
write(*,'("LENS: ",*(g0,1x))')"from",len(str),"to",len(answer),"for a change of",len(str)-len(answer)
write(*,'("CHAR: ",g0)')chr
end subroutine printme
elemental function compact(str,charp) result (outstr)
character(len=*),intent(in) :: str
character(len=1),intent(in) :: charp
character(len=:),allocatable :: outstr
character(len=1) :: ch, last_one
integer :: i, pio
outstr=repeat(' ',len(str))
if(len(outstr)==0)return
last_one=str(1:1)
outstr(1:1)=last_one
pio=1
do i=2,len(str)
ch=str(i:i)
pio=pio+merge(0,1, ch.eq.last_one.and.ch.eq.charp)
outstr(pio:pio)=ch
last_one=ch
enddo
outstr=outstr(:pio)
end function compact
end program main
}
| #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 this program into C but keep the logic exactly as in Fortran. | program main
implicit none
character(len=:),allocatable :: strings(:)
strings=[ character(len=72) :: &
'', &
'"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln', &
'..1111111111111111111111111111111111111111111111111111111111111117777888', &
'I never give ''em hell, I just tell the truth, and they think it''s hell.',&
' --- Harry S Truman' &
]
call printme( trim(strings(1)), ' ' )
call printme( strings(2:4), ['-','7','.'] )
call printme( strings(5), [' ','-','r'] )
contains
impure elemental subroutine printme(str,chr)
character(len=*),intent(in) :: str
character(len=1),intent(in) :: chr
character(len=:),allocatable :: answer
write(*,'(a)')repeat('=',9)
write(*,'("IN: <<<",g0,">>>")')str
answer=compact(str,chr)
write(*,'("OUT: <<<",g0,">>>")')answer
write(*,'("LENS: ",*(g0,1x))')"from",len(str),"to",len(answer),"for a change of",len(str)-len(answer)
write(*,'("CHAR: ",g0)')chr
end subroutine printme
elemental function compact(str,charp) result (outstr)
character(len=*),intent(in) :: str
character(len=1),intent(in) :: charp
character(len=:),allocatable :: outstr
character(len=1) :: ch, last_one
integer :: i, pio
outstr=repeat(' ',len(str))
if(len(outstr)==0)return
last_one=str(1:1)
outstr(1:1)=last_one
pio=1
do i=2,len(str)
ch=str(i:i)
pio=pio+merge(0,1, ch.eq.last_one.and.ch.eq.charp)
outstr(pio:pio)=ch
last_one=ch
enddo
outstr=outstr(:pio)
end function compact
end program main
}
| #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 Fortran. | program main
implicit none
character(len=:),allocatable :: strings(:)
strings=[ character(len=72) :: &
'', &
'"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln', &
'..1111111111111111111111111111111111111111111111111111111111111117777888', &
'I never give ''em hell, I just tell the truth, and they think it''s hell.',&
' --- Harry S Truman' &
]
call printme( trim(strings(1)), ' ' )
call printme( strings(2:4), ['-','7','.'] )
call printme( strings(5), [' ','-','r'] )
contains
impure elemental subroutine printme(str,chr)
character(len=*),intent(in) :: str
character(len=1),intent(in) :: chr
character(len=:),allocatable :: answer
write(*,'(a)')repeat('=',9)
write(*,'("IN: <<<",g0,">>>")')str
answer=compact(str,chr)
write(*,'("OUT: <<<",g0,">>>")')answer
write(*,'("LENS: ",*(g0,1x))')"from",len(str),"to",len(answer),"for a change of",len(str)-len(answer)
write(*,'("CHAR: ",g0)')chr
end subroutine printme
elemental function compact(str,charp) result (outstr)
character(len=*),intent(in) :: str
character(len=1),intent(in) :: charp
character(len=:),allocatable :: outstr
character(len=1) :: ch, last_one
integer :: i, pio
outstr=repeat(' ',len(str))
if(len(outstr)==0)return
last_one=str(1:1)
outstr(1:1)=last_one
pio=1
do i=2,len(str)
ch=str(i:i)
pio=pio+merge(0,1, ch.eq.last_one.and.ch.eq.charp)
outstr(pio:pio)=ch
last_one=ch
enddo
outstr=outstr(:pio)
end function compact
end program main
}
| #include<string.h>
#include<stdlib.h>
#include<stdio.h>
#define COLLAPSE 0
#define SQUEEZE 1
typedef struct charList{
char c;
struct charList *next;
} charList;
int strcmpi(char str1[100],char str2[100]){
int len1 = strlen(str1), len2 = strlen(str2), i;
if(len1!=len2){
return 1;
}
else{
for(i=0;i<len1;i++){
if((str1[i]>='A'&&str1[i]<='Z')&&(str2[i]>='a'&&str2[i]<='z')&&(str2[i]-65!=str1[i]))
return 1;
else if((str2[i]>='A'&&str2[i]<='Z')&&(str1[i]>='a'&&str1[i]<='z')&&(str1[i]-65!=str2[i]))
return 1;
else if(str1[i]!=str2[i])
return 1;
}
}
return 0;
}
charList *strToCharList(char* str){
int len = strlen(str),i;
charList *list, *iterator, *nextChar;
list = (charList*)malloc(sizeof(charList));
list->c = str[0];
list->next = NULL;
iterator = list;
for(i=1;i<len;i++){
nextChar = (charList*)malloc(sizeof(charList));
nextChar->c = str[i];
nextChar->next = NULL;
iterator->next = nextChar;
iterator = nextChar;
}
return list;
}
char* charListToString(charList* list){
charList* iterator = list;
int count = 0,i;
char* str;
while(iterator!=NULL){
count++;
iterator = iterator->next;
}
str = (char*)malloc((count+1)*sizeof(char));
iterator = list;
for(i=0;i<count;i++){
str[i] = iterator->c;
iterator = iterator->next;
}
free(list);
str[i] = '\0';
return str;
}
char* processString(char str[100],int operation, char squeezeChar){
charList *strList = strToCharList(str),*iterator = strList, *scout;
if(operation==SQUEEZE){
while(iterator!=NULL){
if(iterator->c==squeezeChar){
scout = iterator->next;
while(scout!=NULL && scout->c==squeezeChar){
iterator->next = scout->next;
scout->next = NULL;
free(scout);
scout = iterator->next;
}
}
iterator = iterator->next;
}
}
else{
while(iterator!=NULL && iterator->next!=NULL){
if(iterator->c == (iterator->next)->c){
scout = iterator->next;
squeezeChar = iterator->c;
while(scout!=NULL && scout->c==squeezeChar){
iterator->next = scout->next;
scout->next = NULL;
free(scout);
scout = iterator->next;
}
}
iterator = iterator->next;
}
}
return charListToString(strList);
}
void printResults(char originalString[100], char finalString[100], int operation, char squeezeChar){
if(operation==SQUEEZE){
printf("Specified Operation : SQUEEZE\nTarget Character : %c",squeezeChar);
}
else
printf("Specified Operation : COLLAPSE");
printf("\nOriginal %c%c%c%s%c%c%c\nLength : %d",174,174,174,originalString,175,175,175,(int)strlen(originalString));
printf("\nFinal %c%c%c%s%c%c%c\nLength : %d\n",174,174,174,finalString,175,175,175,(int)strlen(finalString));
}
int main(int argc, char** argv){
int operation;
char squeezeChar;
if(argc<3||argc>4){
printf("Usage : %s <SQUEEZE|COLLAPSE> <String to be processed> <Character to be squeezed, if operation is SQUEEZE>\n",argv[0]);
return 0;
}
if(strcmpi(argv[1],"SQUEEZE")==0 && argc!=4){
scanf("Please enter characted to be squeezed : %c",&squeezeChar);
operation = SQUEEZE;
}
else if(argc==4){
operation = SQUEEZE;
squeezeChar = argv[3][0];
}
else if(strcmpi(argv[1],"COLLAPSE")==0){
operation = COLLAPSE;
}
if(strlen(argv[2])<2){
printResults(argv[2],argv[2],operation,squeezeChar);
}
else{
printResults(argv[2],processString(argv[2],operation,squeezeChar),operation,squeezeChar);
}
return 0;
}
|
Rewrite the snippet below in Go so it works the same as the original Fortran code. | program main
implicit none
character(len=:),allocatable :: strings(:)
strings=[ character(len=72) :: &
'', &
'"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln', &
'..1111111111111111111111111111111111111111111111111111111111111117777888', &
'I never give ''em hell, I just tell the truth, and they think it''s hell.',&
' --- Harry S Truman' &
]
call printme( trim(strings(1)), ' ' )
call printme( strings(2:4), ['-','7','.'] )
call printme( strings(5), [' ','-','r'] )
contains
impure elemental subroutine printme(str,chr)
character(len=*),intent(in) :: str
character(len=1),intent(in) :: chr
character(len=:),allocatable :: answer
write(*,'(a)')repeat('=',9)
write(*,'("IN: <<<",g0,">>>")')str
answer=compact(str,chr)
write(*,'("OUT: <<<",g0,">>>")')answer
write(*,'("LENS: ",*(g0,1x))')"from",len(str),"to",len(answer),"for a change of",len(str)-len(answer)
write(*,'("CHAR: ",g0)')chr
end subroutine printme
elemental function compact(str,charp) result (outstr)
character(len=*),intent(in) :: str
character(len=1),intent(in) :: charp
character(len=:),allocatable :: outstr
character(len=1) :: ch, last_one
integer :: i, pio
outstr=repeat(' ',len(str))
if(len(outstr)==0)return
last_one=str(1:1)
outstr(1:1)=last_one
pio=1
do i=2,len(str)
ch=str(i:i)
pio=pio+merge(0,1, ch.eq.last_one.and.ch.eq.charp)
outstr(pio:pio)=ch
last_one=ch
enddo
outstr=outstr(:pio)
end function compact
end program main
}
| 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 language-to-language conversion: from Fortran to Java, same semantics. | program main
implicit none
character(len=:),allocatable :: strings(:)
strings=[ character(len=72) :: &
'', &
'"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln', &
'..1111111111111111111111111111111111111111111111111111111111111117777888', &
'I never give ''em hell, I just tell the truth, and they think it''s hell.',&
' --- Harry S Truman' &
]
call printme( trim(strings(1)), ' ' )
call printme( strings(2:4), ['-','7','.'] )
call printme( strings(5), [' ','-','r'] )
contains
impure elemental subroutine printme(str,chr)
character(len=*),intent(in) :: str
character(len=1),intent(in) :: chr
character(len=:),allocatable :: answer
write(*,'(a)')repeat('=',9)
write(*,'("IN: <<<",g0,">>>")')str
answer=compact(str,chr)
write(*,'("OUT: <<<",g0,">>>")')answer
write(*,'("LENS: ",*(g0,1x))')"from",len(str),"to",len(answer),"for a change of",len(str)-len(answer)
write(*,'("CHAR: ",g0)')chr
end subroutine printme
elemental function compact(str,charp) result (outstr)
character(len=*),intent(in) :: str
character(len=1),intent(in) :: charp
character(len=:),allocatable :: outstr
character(len=1) :: ch, last_one
integer :: i, pio
outstr=repeat(' ',len(str))
if(len(outstr)==0)return
last_one=str(1:1)
outstr(1:1)=last_one
pio=1
do i=2,len(str)
ch=str(i:i)
pio=pio+merge(0,1, ch.eq.last_one.and.ch.eq.charp)
outstr(pio:pio)=ch
last_one=ch
enddo
outstr=outstr(:pio)
end function compact
end program main
}
|
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 Fortran code into Java without altering its purpose. | program main
implicit none
character(len=:),allocatable :: strings(:)
strings=[ character(len=72) :: &
'', &
'"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln', &
'..1111111111111111111111111111111111111111111111111111111111111117777888', &
'I never give ''em hell, I just tell the truth, and they think it''s hell.',&
' --- Harry S Truman' &
]
call printme( trim(strings(1)), ' ' )
call printme( strings(2:4), ['-','7','.'] )
call printme( strings(5), [' ','-','r'] )
contains
impure elemental subroutine printme(str,chr)
character(len=*),intent(in) :: str
character(len=1),intent(in) :: chr
character(len=:),allocatable :: answer
write(*,'(a)')repeat('=',9)
write(*,'("IN: <<<",g0,">>>")')str
answer=compact(str,chr)
write(*,'("OUT: <<<",g0,">>>")')answer
write(*,'("LENS: ",*(g0,1x))')"from",len(str),"to",len(answer),"for a change of",len(str)-len(answer)
write(*,'("CHAR: ",g0)')chr
end subroutine printme
elemental function compact(str,charp) result (outstr)
character(len=*),intent(in) :: str
character(len=1),intent(in) :: charp
character(len=:),allocatable :: outstr
character(len=1) :: ch, last_one
integer :: i, pio
outstr=repeat(' ',len(str))
if(len(outstr)==0)return
last_one=str(1:1)
outstr(1:1)=last_one
pio=1
do i=2,len(str)
ch=str(i:i)
pio=pio+merge(0,1, ch.eq.last_one.and.ch.eq.charp)
outstr(pio:pio)=ch
last_one=ch
enddo
outstr=outstr(:pio)
end function compact
end program main
}
|
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();
}
}
|
Can you help me rewrite this code in Python instead of Fortran, keeping it the same logically? | program main
implicit none
character(len=:),allocatable :: strings(:)
strings=[ character(len=72) :: &
'', &
'"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln', &
'..1111111111111111111111111111111111111111111111111111111111111117777888', &
'I never give ''em hell, I just tell the truth, and they think it''s hell.',&
' --- Harry S Truman' &
]
call printme( trim(strings(1)), ' ' )
call printme( strings(2:4), ['-','7','.'] )
call printme( strings(5), [' ','-','r'] )
contains
impure elemental subroutine printme(str,chr)
character(len=*),intent(in) :: str
character(len=1),intent(in) :: chr
character(len=:),allocatable :: answer
write(*,'(a)')repeat('=',9)
write(*,'("IN: <<<",g0,">>>")')str
answer=compact(str,chr)
write(*,'("OUT: <<<",g0,">>>")')answer
write(*,'("LENS: ",*(g0,1x))')"from",len(str),"to",len(answer),"for a change of",len(str)-len(answer)
write(*,'("CHAR: ",g0)')chr
end subroutine printme
elemental function compact(str,charp) result (outstr)
character(len=*),intent(in) :: str
character(len=1),intent(in) :: charp
character(len=:),allocatable :: outstr
character(len=1) :: ch, last_one
integer :: i, pio
outstr=repeat(' ',len(str))
if(len(outstr)==0)return
last_one=str(1:1)
outstr(1:1)=last_one
pio=1
do i=2,len(str)
ch=str(i:i)
pio=pio+merge(0,1, ch.eq.last_one.and.ch.eq.charp)
outstr(pio:pio)=ch
last_one=ch
enddo
outstr=outstr(:pio)
end function compact
end program main
}
| 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 Fortran. | program main
implicit none
character(len=:),allocatable :: strings(:)
strings=[ character(len=72) :: &
'', &
'"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln', &
'..1111111111111111111111111111111111111111111111111111111111111117777888', &
'I never give ''em hell, I just tell the truth, and they think it''s hell.',&
' --- Harry S Truman' &
]
call printme( trim(strings(1)), ' ' )
call printme( strings(2:4), ['-','7','.'] )
call printme( strings(5), [' ','-','r'] )
contains
impure elemental subroutine printme(str,chr)
character(len=*),intent(in) :: str
character(len=1),intent(in) :: chr
character(len=:),allocatable :: answer
write(*,'(a)')repeat('=',9)
write(*,'("IN: <<<",g0,">>>")')str
answer=compact(str,chr)
write(*,'("OUT: <<<",g0,">>>")')answer
write(*,'("LENS: ",*(g0,1x))')"from",len(str),"to",len(answer),"for a change of",len(str)-len(answer)
write(*,'("CHAR: ",g0)')chr
end subroutine printme
elemental function compact(str,charp) result (outstr)
character(len=*),intent(in) :: str
character(len=1),intent(in) :: charp
character(len=:),allocatable :: outstr
character(len=1) :: ch, last_one
integer :: i, pio
outstr=repeat(' ',len(str))
if(len(outstr)==0)return
last_one=str(1:1)
outstr(1:1)=last_one
pio=1
do i=2,len(str)
ch=str(i:i)
pio=pio+merge(0,1, ch.eq.last_one.and.ch.eq.charp)
outstr(pio:pio)=ch
last_one=ch
enddo
outstr=outstr(:pio)
end function compact
end program main
}
| 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 Fortran snippet to VB and keep its semantics consistent. | program main
implicit none
character(len=:),allocatable :: strings(:)
strings=[ character(len=72) :: &
'', &
'"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln', &
'..1111111111111111111111111111111111111111111111111111111111111117777888', &
'I never give ''em hell, I just tell the truth, and they think it''s hell.',&
' --- Harry S Truman' &
]
call printme( trim(strings(1)), ' ' )
call printme( strings(2:4), ['-','7','.'] )
call printme( strings(5), [' ','-','r'] )
contains
impure elemental subroutine printme(str,chr)
character(len=*),intent(in) :: str
character(len=1),intent(in) :: chr
character(len=:),allocatable :: answer
write(*,'(a)')repeat('=',9)
write(*,'("IN: <<<",g0,">>>")')str
answer=compact(str,chr)
write(*,'("OUT: <<<",g0,">>>")')answer
write(*,'("LENS: ",*(g0,1x))')"from",len(str),"to",len(answer),"for a change of",len(str)-len(answer)
write(*,'("CHAR: ",g0)')chr
end subroutine printme
elemental function compact(str,charp) result (outstr)
character(len=*),intent(in) :: str
character(len=1),intent(in) :: charp
character(len=:),allocatable :: outstr
character(len=1) :: ch, last_one
integer :: i, pio
outstr=repeat(' ',len(str))
if(len(outstr)==0)return
last_one=str(1:1)
outstr(1:1)=last_one
pio=1
do i=2,len(str)
ch=str(i:i)
pio=pio+merge(0,1, ch.eq.last_one.and.ch.eq.charp)
outstr(pio:pio)=ch
last_one=ch
enddo
outstr=outstr(:pio)
end function compact
end program main
}
| 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
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.