10 Replies - 13622 Views - Last Post: 13 August 2010 - 04:59 AM

#1 AdamSpeight2008  Icon User is offline

  • MrCupOfT
  • member icon


Reputation: 2270
  • View blog
  • Posts: 9,496
  • Joined: 29-May 08

Unique Ways To Accomplish A Task. (Task 3)

Posted 11 August 2010 - 05:41 PM

The challenge is to write a function that take to parameters (a string and a dictionary(of Char,Char) and returns a string. The returned string

Dream In Code
D -> a
a -> D
Space -> X

Returns: areDmXInCode

Public Function MultipleLetterReplace(ByVal In As String,ByVal D As Dictionary(Of Char,Char)) As String

End Function



Lets see your attempts.

Is This A Good Question/Topic? 0
  • +

Replies To: Unique Ways To Accomplish A Task. (Task 3)

#2 woodjom  Icon User is offline

  • D.I.C Addict
  • member icon

Reputation: 29
  • View blog
  • Posts: 549
  • Joined: 08-May 08

Re: Unique Ways To Accomplish A Task. (Task 3)

Posted 11 August 2010 - 06:21 PM

View PostAdamSpeight2008, on 11 August 2010 - 06:41 PM, said:

The challenge is to write a function that take to parameters (a string and a dictionary(of Char,Char) and returns a string. The returned string

Dream In Code
D -> a
a -> D
Space -> X

Returns: areDmXInCode

Public Function MultipleLetterReplace(ByVal In As String,ByVal D As Dictionary(Of Char,Char)) As String

End Function



Lets see your attempts.


Would this be with .Net 4 or 2?

As well dont you mean it is supposed to
Returns: areDmXInXCode
Was This Post Helpful? 0
  • +
  • -

#3 woodjom  Icon User is offline

  • D.I.C Addict
  • member icon

Reputation: 29
  • View blog
  • Posts: 549
  • Joined: 08-May 08

Re: Unique Ways To Accomplish A Task. (Task 3)

Posted 11 August 2010 - 06:57 PM

Not that it mattered but here you go.

Private Function MultipleLetterReplace(ByVal [in] As String, ByVal repl As Dictionary(Of Char, Char)) As String
  Dim result As String = Nothing

  For Each ch As Char In [in]
    If repl.ContainsKey(ch) Then
	result &= repl.Item(ch)
    Else
	result &= ch
    End If
  Next

  Return result
End Function



Proof of purchase attached.
Attached Image

This post has been edited by woodjom: 11 August 2010 - 06:58 PM

Was This Post Helpful? 0
  • +
  • -

#4 T3hC13h  Icon User is offline

  • D.I.C Regular

Reputation: 65
  • View blog
  • Posts: 337
  • Joined: 05-February 08

Re: Unique Ways To Accomplish A Task. (Task 3)

Posted 12 August 2010 - 08:45 AM

Attempt one:

    Public Function MultipleLetterReplace(ByVal [In] As String, ByVal D As Dictionary(Of Char, Char)) As String
        Dim cReturn() As Char = [In].ToCharArray()
        For i As Integer = 0 To [In].Length - 1
            If D.ContainsKey([In](i)) Then cReturn(i) = D([In](i))
        Next
        Return Unicode.GetString(Unicode.GetBytes(cReturn))
    End Function



Numba tew:

    Public Function MultipleLetterReplace(ByVal [In] As String, ByVal D As Dictionary(Of Char, Char)) As String
        Dim dtChars As New Dictionary(Of Char, List(Of Integer))
        For i As Integer = 0 To [In].Length - 1
            Dim cCur As Char = [In](i)
            If dtChars.ContainsKey(cCur) Then
                dtChars(cCur).Add(i)
            Else
                dtChars.Add(cCur, New List(Of Integer))
                dtChars(cCur).Add(i)
            End If
        Next
        Dim cReturn([In].Length - 1) As Char
        For Each kvp As KeyValuePair(Of Char, List(Of Integer)) In dtChars
            Dim cNew As Char
            If D.ContainsKey(kvp.Key) Then cNew = D(kvp.Key) Else cNew = kvp.Key
            For Each i As Integer In kvp.Value
                cReturn(i) = cNew
            Next
        Next
        Return Unicode.GetString(Unicode.GetBytes(cReturn))
    End Function



3:


Imports System.Text
Imports System.Text.Encoding
Imports System.Reflection
Imports System.CodeDom.Compiler
Module Module1
    Sub Main()
        Dim d As New Dictionary(Of Char, Char)
        d.Add("D"c, "a"c)
        d.Add("a"c, "D"c)
        d.Add(" "c, "X"c)
        Console.WriteLine(MultipleLetterReplace("Dream In Code", d))
        Console.ReadLine()
    End Sub
    Public Function MultipleLetterReplace(ByVal [In] As String, ByVal D As Dictionary(Of Char, Char)) As String
        Dim sb As New StringBuilder
        With sb
            .AppendLine("Namespace Stubb")
            .AppendLine("Class Stubb")
            .AppendLine("   Sub New()")
            .AppendLine("   End Sub")
            .AppendLine("   Public Function GetString()")
            .AppendLine("       Dim sIn as String = " & Chr(34) & [In] & Chr(34))
            .AppendLine("       Dim sOut as String = String.Empty")
            .AppendLine("       For Each c as Char in sIn")
            .AppendLine("           Select Case c")
            For Each kvp As KeyValuePair(Of Char, Char) In D
                .AppendLine("               Case " & Chr(34) & kvp.Key & Chr(34))
                .AppendLine("                   sOut &= " & Chr(34) & kvp.Value & Chr(34))
            Next
            .AppendLine("               Case Else")
            .AppendLine("                   sOut &= c")
            .AppendLine("           End Select")
            .AppendLine("       Next")
            .AppendLine("       Return sOut")
            .AppendLine("   End Function")
            .AppendLine("End Class")
            .AppendLine("End Namespace")
        End With
        Dim loCompiler As VBCodeProvider = CodeDomProvider.CreateProvider("VB")
        Dim langCompilerInfo As CompilerInfo = CodeDomProvider.GetCompilerInfo("VB")

        Dim loParameters As CompilerParameters = langCompilerInfo.CreateDefaultCompilerParameters()

        loParameters.ReferencedAssemblies.Add("System.dll")
        loParameters.GenerateInMemory = True
        Dim loCompiled As CompilerResults = loCompiler.CompileAssemblyFromSource(loParameters, sb.ToString)
        If loCompiled.Errors.HasErrors Then
            For Each Err As CompilerError In loCompiled.Errors
                Debug.WriteLine(Err.Line.ToString & ":" & Err.ErrorText)
            Next
        Else

            Dim loAssembly As Assembly = loCompiled.CompiledAssembly
            Dim loObject As Object = loAssembly.CreateInstance("Stubb.Stubb")
            If loObject Is Nothing Then
                Debug.WriteLine("Could not load class")
                Return String.Empty
            End If
            Dim loResult As Object = loObject.GetType().InvokeMember("GetString", BindingFlags.InvokeMethod, Nothing, loObject, Nothing)
            Return loResult.ToString
        End If
        Return String.Empty
    End Function
End Module


This post has been edited by T3hC13h: 12 August 2010 - 01:48 PM

Was This Post Helpful? 2
  • +
  • -

#5 Curtis Rutland  Icon User is offline

  • (╯□)╯︵ (~ .o.)~
  • member icon


Reputation: 4559
  • View blog
  • Posts: 7,980
  • Joined: 08-June 10

Re: Unique Ways To Accomplish A Task. (Task 3)

Posted 12 August 2010 - 02:21 PM

Rephrased slightly, this could actually be a handy extension method. I called it "ReplaceMany", to compliment my old "RemoveMany".

In VB.NET:
Imports System.Text
Imports System.Runtime.CompilerServices

Module Module1
    Sub Main()
        Dim dict As New Dictionary(Of Char, Char)
        dict.Add("D"c, "a"c)
        dict.Add("a"c, "D"c)
        dict.Add(" "c, "X"c)
        Console.WriteLine("Dream In Code".ReplaceMany(dict))
        Console.ReadKey()
    End Sub
End Module

Public Module Extensions
    <Extension()>
    Public Function ReplaceMany(ByVal dirty As String, ByVal replacer As Dictionary(Of Char, Char)) As String
        Dim sb As New StringBuilder
        dirty.ToList().ForEach(Function(x) sb.Append(If(replacer.ContainsKey(x), replacer(x), x)))
        Return sb.ToString()
    End Function
End Module


In C# (which I admit I had to do it in first, then translate):
using System;
using System.Linq;
using System.Collections.Generic;
using System.Text;

namespace HelloWorld
{
    class Program
    {
        static void Main(string[] args)
        {
            Dictionary<char, char> dict = new Dictionary<char, char>();
            dict.Add('D', 'a');
            dict.Add('a', 'D');
            dict.Add(' ', 'X');
            Console.WriteLine("Dream In Code".ReplaceMany(dict));
            Console.ReadKey();
        }
    }

    public static class Extensions
    {        
        public static string ReplaceMany(this string dirty, Dictionary<char, char> replacer)
        {
            StringBuilder sb = new StringBuilder();
            dirty.ToList().ForEach(x => sb.Append(replacer.ContainsKey(x) ? replacer[x] : x));
            return sb.ToString();
        }
    }
}


Soon to come in F# as well.

This post has been edited by insertAlias: 12 August 2010 - 02:25 PM

Was This Post Helpful? 1
  • +
  • -

#6 AdamSpeight2008  Icon User is offline

  • MrCupOfT
  • member icon


Reputation: 2270
  • View blog
  • Posts: 9,496
  • Joined: 29-May 08

Re: Unique Ways To Accomplish A Task. (Task 3)

Posted 12 August 2010 - 02:50 PM

Yeah I could have phrased the challenge a bit better.
I was thinking of the issue.
replace("D",a).Replace("a","D")


Any how.

   Public Function MultipleLetterReplace(ByVal [in] As String, ByVal D As Dictionary(Of Char, Char)) As String
    Return [in].ToCharArray.Select(Function(c) If(D.ContainsKey(c), D(c), c)).Aggregate(Of String)("", Function(prev, curr) prev & curr)
  End Function

Was This Post Helpful? 0
  • +
  • -

#7 Curtis Rutland  Icon User is offline

  • (╯□)╯︵ (~ .o.)~
  • member icon


Reputation: 4559
  • View blog
  • Posts: 7,980
  • Joined: 08-June 10

Re: Unique Ways To Accomplish A Task. (Task 3)

Posted 12 August 2010 - 03:00 PM

You know, I was using Aggregate too, but I went with the ForEach. Aggregate is a little more graceful.
Was This Post Helpful? 0
  • +
  • -

#8 AdamSpeight2008  Icon User is offline

  • MrCupOfT
  • member icon


Reputation: 2270
  • View blog
  • Posts: 9,496
  • Joined: 29-May 08

Re: Unique Ways To Accomplish A Task. (Task 3)

Posted 12 August 2010 - 03:25 PM

Slight variant (specify replacement chars as parameters)
 <Runtime.CompilerServices.Extension()>
  Public Function MultipleLetterReplace(ByVal [in] As String, ByVal ParamArray D As Char()) As String
    Dim dd As New Dictionary(Of Char, Char)
    Dim e = D.GetEnumerator
    Dim tmp As Char
    While e.MoveNext
      tmp = e.Current
      If e.MoveNext() = False Then Exit While
      dd.Add(tmp, e.Current)
    End While
    Return [in].ToCharArray.Select(Function(c) If(dd.ContainsKey(c), dd(c), c)).Aggregate(Of String)("", Function(prev, curr) prev & curr)
  End Function


Example
   Dim rs2 = "dream in code".MultipleLetterReplace("D", "a", "a", "D", " ", "x")
 

Was This Post Helpful? 0
  • +
  • -

#9 Curtis Rutland  Icon User is offline

  • (╯□)╯︵ (~ .o.)~
  • member icon


Reputation: 4559
  • View blog
  • Posts: 7,980
  • Joined: 08-June 10

Re: Unique Ways To Accomplish A Task. (Task 3)

Posted 12 August 2010 - 03:48 PM

Ha, I had the idea to use Tuples.

<Extension()>
Public Function ReplaceMany(ByVal dirty As String, ByVal ParamArray pairs As Tuple(Of Char, Char)()) As String
    Dim sb As New StringBuilder()
    dirty.ToList().ForEach( _
        Function(x) sb.Append( _
            If(pairs.Any(Function(y) y.Item1 = x), _
               pairs.First(Function(y) y.Item1 = x).Item2, _
               x)))
    Return sb.ToString()
End Function


Was This Post Helpful? 0
  • +
  • -

#10 AdamSpeight2008  Icon User is offline

  • MrCupOfT
  • member icon


Reputation: 2270
  • View blog
  • Posts: 9,496
  • Joined: 29-May 08

Re: Unique Ways To Accomplish A Task. (Task 3)

Posted 12 August 2010 - 05:35 PM

Similar to yours but I've removed the if statement.
  <Extension()>
  Public Function ReplaceMany(ByVal dirty As String, ByVal ParamArray pairs() As Tuple(Of Char, Char)) As String
    Return dirty.Aggregate(Of System.Text.StringBuilder)(
      New System.Text.StringBuilder,
       Function(P, C)
         Return P.Append(pairs.Where(
           Function(y) (y.Item1 = C)).DefaultIfEmpty(New Tuple(Of Char, Char)(C, C))(0).Item2)
       End Function).ToString
  End Function


Was This Post Helpful? 0
  • +
  • -

#11 Goethals  Icon User is offline

  • D.I.C Head

Reputation: 25
  • View blog
  • Posts: 145
  • Joined: 14-April 09

Re: Unique Ways To Accomplish A Task. (Task 3)

Posted 13 August 2010 - 04:59 AM

    Private Function ReplaceManny(ByVal Data As String, ByVal Dic As Dictionary(Of Char, Char)) As String
        Dim Original As Char() = Data.ToCharArray
        Dim ToReturn As Char() = Data.ToCharArray
        For Each Item As KeyValuePair(Of Char, Char) In Dic
            For Teller As Integer = 0 To Original.Length - 1
                Dim C As Char = Original(Teller)
                If Item.Key = C Then
                    ToReturn(Teller) = Item.Value
                End If
            Next
        Next
        Return ToReturn
    End Function


Was This Post Helpful? 0
  • +
  • -

Page 1 of 1