// Set of utilities to encode a string into different formats.packageencoderimport("unicode""strings")// Encode a given string into a format comprised of left and right parens. If one character is present multiple times in the string, the left parens will be used to encode this character, otherwise, the right parens will be used.funcEncodeDuplicateParens(inputstring)string{encoded:=strings.Builder{}occurrences:=make(map[rune]int)for_,character:=rangeinput{occurrences[unicode.ToLower(character)]++}for_,character:=rangeinput{ifoccurrences[unicode.ToLower(character)]>1{encoded.WriteRune(')')}else{encoded.WriteRune('(')}}returnencoded.String()}
$touch encoder_test.go
packageencoder_testimport("encoder""fmt""testing")funcTestWithMultipleStrings(t*testing.T){valuesExpectations:=map[string]string{"(( @":"))((","Success":")())())","din":"(((","recede":"()()()",}forvalue,expectation:=rangevaluesExpectations{result:=encoder.EncodeDuplicateParens(value)ifexpectation!=result{t.Errorf("Expected encode.EncodeDuplicateParens(%q) to equal %q but got %q.",value,expectation,result)}}}funcBenchmarkEncodeDuplicateParens(b*testing.B){forindex:=0;index<b.N;index++{encoder.EncodeDuplicateParens("Success")}}funcExampleEncodeDuplicateParens(){values:=[]string{"(( @","Success","din","recede",}for_,value:=rangevalues{fmt.Println(encoder.EncodeDuplicateParens(value));}// Output: ))((// )())())// (((// ()()()}
$go test-cover-bench.goos: linux
goarch: amd64
pkg: encoder
BenchmarkEncodeDuplicateParens-4 4961448 256 ns/op
PASS
coverage: 100.0% of statements
ok encoder 1.516s
pubfndub_enc(inp:String)->String{letlowered=inp.to_lowercase();lowered.chars().map(|c|{letmutfinder=lowered.chars().filter(|r|*r==c);finder.next();// existsiffinder.next().is_some(){// found at least once more")"}else{"("}}).collect()}
constencodeDuplicate=str=>{//make a frequency mapconstfreqMap=[...str.toLowerCase()].reduce((acc,val)=>{acc[val]=acc[val]+1||1;returnacc;},{});//return the mapped str return[...str.toLowerCase()].map(e=>freqMap[e]==1?'(':')').join('');}
Not that slow :) Better than anything that searched/scanned or did an indexOf for sure! You know I like that || 1 as well, I always do (acc[val] || 0) + 1 - but that is much neater. Borrowing that.
I am an OpenEdge (aka Progress) developer that loves clean code and good looking applications that are easy to use. My main pet project is the Progress DataDigger
/* Progress 4GL Daily Challenge #259
*/
FUNCTION dupDecode RETURNS CHARACTER (pcString AS CHARACTER):
DEFINE VARIABLE i AS INTEGER NO-UNDO.
DO i = 1 TO LENGTH(pcString):
pcString = REPLACE( pcString
, SUBSTRING(pcString,i,1)
, STRING(NUM-ENTRIES(pcString,SUBSTRING(pcString,i,1)) = 2,'(/)')
).
END.
RETURN pcString.
END FUNCTION.
MESSAGE dupDecode('Success')
VIEW-AS ALERT-BOX INFORMATION BUTTONS OK.
Boring is good. I usually avoid oneliners and magical solutions.
A more "production ready" version of the above:
'''A "duplicate encoder"s.
Based on https://dev.to/thepracticaldev/daily-challenge-259-duplicate-encoder-2e8l
When running on command line, encodes standard input.
You can also use the following args:
-t : Executes automated testing
-h : Shows this help'''defencode(text):'''Convert a string to a new string where each character in the new string
is "(" if that character appears only once in the original string, or ")"
if that character appears more than once in the original string.
Examples:
>>> encode('Success')
')())())'
>>> encode('(( @')
'))(('
>>> encode('din')
'((('
>>> encode('recede')
'()()()'
'''encoded=''forcharintext:encoded+=replace_char(char,text)returnencodeddefreplace_char(char,text):'''Returns ')' if char appears more than once in text. Otherwise,
returns '('. Case insensitive. Examples:
>>> replace_char('a', 'banana')
')'
>>> replace_char('B', 'banana')
'('
'''iftext.lower().count(char.lower())>1:return')'return'('if__name__=='__main__':importsysifsys.argv[-1]=='-t':importdoctestdoctest.testmod()elifsys.argv[-1]=='-h':importpydocprint(pydoc.getdoc(sys.modules[__name__]))else:print(encode(sys.stdin.read()))
stringencodeDuplicate(strings){// stores the count of corresponding character (lower cased) in sunordered_map<char,int>charCount;for(charc:s)charCount[tolower(c)]++;stringans="";for(charc:s)ans+=(charCount[tolower(c)]>1)?')':'(';returnans;}
I'm a little late, but rather than solving the problem I instead took the different approaches people posted, wrote them in D (dlang.org) and did some basic performance ploting.
I didn't really want to solve the challenge per se, so instead I took the top comments for implementation and wrote them in D Lang.
For clarity these are all implemented in D and do not reflect the language performance that the implementation is based on.
The "Haskel" implementation utilizes a range based map/filter approach to detecting duplicates.
The "PHP" implementation utilizes a nested loop apporach to intentify that the character occurs again.
The "Pointer" implementation was just something I wanted to try. It duplicates the array so it is mutable
after which point it does not loop over the arry twice and instead stores pointers to the location of the
same character. It takes quite a bit for this approach to see any performance gain.
I might do more work on this and write up my own post about what I did. Keep in mind that I use the terms 'php' and 'haskel' not to indicate the performance of those languages... it was just the language utilized for the approach taken. All timings are from D.
Javascript solution:
Neat!
What is this syntax at the end?
join``I always use
.join('').That is Tagged template literals, to save 2 character :D
I forgot all about that syntax. I've probably only used it a few times.
My Haskell solution:
Go
Python solution 🐍
Here is the simple approach with nested for loops with PHP:
In Rust – playground link (with tests)
Why not use std::str::matches to iterate over the same chars?
I suppose that is a valid alternative. Just not the first thing that came to mind ...
I just love how Rust has a helpful method for about everything in its std/core libs.
A simple (and somewhat slow) JS solution:
Not that slow :) Better than anything that searched/scanned or did an indexOf for sure! You know I like that || 1 as well, I always do (acc[val] || 0) + 1 - but that is much neater. Borrowing that.
Same to me
|| 0TypeScript:
Rust 🦀🦀🦀🦀solution:🦀🦀🦀🦀🦀 🦀
Python:
A magical Python solution:
A boring Python solution:
Boring is good. I usually avoid oneliners and magical solutions.
A more "production ready" version of the above:
Here is a C++ solution,
I'm a little late, but rather than solving the problem I instead took the different approaches people posted, wrote them in D (dlang.org) and did some basic performance ploting.
An attempt to capture performance with different implementation approaches for a Challenge
Dev.to has a daily challenge and I happened upon the Duplicate Encoder #259 for 2020
I didn't really want to solve the challenge per se, so instead I took the top comments for implementation and wrote them in D Lang.
For clarity these are all implemented in D and do not reflect the language performance that the implementation is based on.
The "Haskel" implementation utilizes a range based map/filter approach to detecting duplicates.
The "PHP" implementation utilizes a nested loop apporach to intentify that the character occurs again.
The "Pointer" implementation was just something I wanted to try. It duplicates the array so it is mutable after which point it does not loop over the arry twice and instead stores pointers to the location of the same character. It takes quite a bit for this approach to see any performance gain.
I might do more work on this and write up my own post about what I did. Keep in mind that I use the terms 'php' and 'haskel' not to indicate the performance of those languages... it was just the language utilized for the approach taken. All timings are from D.
Erlang solution, though not sure this would be the most efficient. I am still learning the language :)
🐍
Clojure
Here is a simple python code:
