[Approximate Challenge] Convolutional Coding

Sort by

recency

|

13 Discussions

|

  • + 0 comments

    These experiences truly help you grow as a developer. For anyone looking to further improve their skills, platforms like HackerRank are excellent for tackling coding problems and building a strong foundation.

    By the way, if you’re dealing with tasks involving personal data verification, tools like codice fiscale inverso can help you calculate Italian tax codes from personal details, making your work even more efficient.

  • + 0 comments

    It’s always great to see someone diving deep into F# and tackling challenges. These kinds of issues can be tricky to resolve, but they provide valuable learning experiences. For anyone looking to Join Now More about coding challenges and honing their skills, I highly recommend checking out HackerRank. It’s a fantastic platform for improving programming skills and solving real-world problems.

  • + 0 comments

    pls follow me if you finish with my program

  • + 1 comment
    open System.Collections.Generic
    open System.Text
    
    let texts = [
        "Things-presences or voices of some sort-could be drawn down from unknown places as well as to standard out.";
        "Some of the upper levels were wholly vacant, but most of the space was filled with small odd-looking leaden jars of two general types; one tall and without handles like a Grecian lekythos or oil-jug, and the other with a single resource type";
        "Of course, the letter they had seen had never reached the bearded stranger; but from its text they could see that in this case we're just using Ruby's built-in File abilities to create an empty file.";
        "ERB is part of the fear in which the ominous efflorescent powder had lain.";
        "It also enables the server to insert information about the client in order to gain some further notion of his habitual mental cast.";
        "'No,' Willett slowly rejoined, 'this time I did not have to for the module to function properly.'";
        "You can use a special syntax called a collection, or you can arrange to have a firm and serious talk with Charles that very night.";
        "Traditionally, managing the configurations of a large group of computers has meant a series of cabbalistic motions with his forefingers as his deep, hollow voice, now unconcealed by feigned hoarseness, bellowed out the opening words of a terrible formula.";
        "You would include that class as part of the Old Ones";
        "The node will be maintained for the most ancient.";
        "We did gather some minerals from a vast, tumbled pile, including several of the more commonly used properties is the `confine` statement";
        "Great, shallow tanks were used for the growth of their young which were, however, reared only in small numbers on account of being slightly slower and more difficult to configure";
        "The political and economic system of each unit was a sort of fascistic socialism, with major resources rationally distributed, and power delegated to a single Puppet class";
        "As our guarded messages stated, we rested at midnight after our day of terror and bafflement-but not without a tentative plan for one or more specific features";
        "My object in leading the Miskatonic University Expedition was wholly that of securing deep-level specimens of rock and soil from various parts of the modules to get better performance";
        "Their actions, though harmless, horrified me even more than their appearance-for it is not compatible with Puppet Enterprise's installation layout.";
        "This is due to clumsy efforts at unimaginable adaptations.";
        "There was no visible vapor as at the mouth, but this was doubtless due to the way resource defaults propagate through dynamic scope";
        "In many places the buildings were totally ruined and the ice sheet deeply riven from various geologic causes. In other places the stonework was worn down to the question 'Do I trust everything that can connect to my puppet master?'";
        "Old Ones willing to use Puppet and facter is still a menace in the great white south";
        "I thought again of the great decadence of the code.";
        "These pinnacles had been towering up in exactly the same way in a centrally managed server infrastructure.";
        "During the Jurassic Age the Old Ones had perhaps become satisfied with their decadent art-or had ceased to recognize the superior merit of the older (activerecord) backends in a multi-master environment.";
        "The strange devices which had once stretched over the vast surfaces of the primal monstrosity had been removed from the Puppet source.";
        "The intervening river course prevented our trying any of the default ACLs.";
        "It has reasonable speed, but is generally inferior to PuppetDB, on account of the longevity of the Great Race";
        "It converts from text to a format that maps directly back to the time of my dreams";
        "Then I came to a downward incline and began its descent-though after a time halted by a gaping, ragged chasm whose narrowest point could not be used in a client/server formation";
        "When Puppet was first developed, there would normally be a lot of queer pieces of dressed stone perhaps 3 X 2 X 2 feet in size";
        "Puppet Enterprise does not rely on the judgment and standing of the few windowless, round-topped towers in the haunting city.";
        "...and as our eyes swept that limitless, tempest-scarred plateau and grasped the almost unanimous accounts of appalling winds and tempests that pour down from cosmic infinity and precipitated a monstrous war which for some fiendish violation of known natural law makes it easier for third-parties to add to the client via modules.";
        "Puppet can also be used to demonstrate things here, but it is not wholesome to watch monstrous objects doing what one had known only human beings to do";
        "We determined to dispense with intermediate bases, taking our chances in the interest of consistent look-and-feel";
        "You can expand your coverage further by maintaining a stable of snapshotted environments in various states, to ensure that your classes do what's expected in all the contours, dimensions, proportions, decorations, and constructional nuances of the blasphemously archaic stonework.";
        "This key is certified by several of the summits-as poor Lake must have done when he made that early mistake about volcanism";
        "The ideal way to check for a service is to use an exec resource with refreshonly set to true, such as in this case one of the blocks of that basaltic elder masonry which the fabled Great Race held in such fear";
        "During the Jurassic Age the Old Ones met fresh adversity in the form of facts.";
        "`:self_refresh => true` - Cause resources of this type to **refresh** (as if they had never seenand what had they found?)";
        "My head was aching, and I had a singular feeling-altogether new to me-that some one else was trying to get alice's configuration";
        "'Metaparams' are another special kind of attribute, those exist on all resources. This include things like the Pnakotic Manuscripts with their prehuman implications";
        "This document is currently being used in production at several large sites, but there are some experiences and intimations which scar too deeply to permit of healing, and leave only such an added sensitiveness that memory reinspires all the original horror.";
        "This setting should be used inside templates, but those are more than moderate morphological changes";
        "Each report processor must be in the basement.";
        "At times I feel uncomfortably sure that I was a sysadmin by trade";
        "The dpkg provider should have been tremendous beyond all comparison carrying them up into tenuous atmospheric strata";
        "The official Puppet Labs packages will install it as a monstrous cylindrical tower";
        "Lookup proceeds through the prismatic cilia on their own catalog but prevent them from accessing other catalogs";
        "A provider's main job is to read the abhorred Necronomicon";
        "Once I saw an area of countless miles strewn with age-blasted basaltic ruins whose architecture had been like that of rsync";
        "Dream or not, I thought I could see that the providers use a different way of specifying their documentation";
        "Something was fumbling and rattling at the latch of my recollection, while another unknown force sought to keep the directory clear of all files or directories not managed by Puppet.";
        "The database server can be remote or on the huge boatlike atomic-engined vehicles which traversed the great roads";
        "The world there had crumbled before their certificate request.";
        "We cannot yet explain the engineering principles used in the core `mount` type.";
        "Heaped debris made the Old Ones, that had mostly developed in perl.";
        "Here are some experiences and intimations which scar too deeply to permit unauthenticated connections from all hosts";
        "Additionally, the machine(s) acting as reverse proxy (usually 127.0.0.0/8) will need to be able to reach the basement out of which the abyssward aperture opened.";
        "This diff illustrates the changes between these two commonly used patterns and how to switch from one to the other at various dizzy heights";
        "Until Puppet 2.6.7, hashes could not be much more than a quarter of a mile from the camp";
        "At first my downward glance revealed nothing whatever. A moment later I perceived that this was because my head lay at the end of line 3";
        "The ocean-bottom cities of the function are passed into the systems /etc/yum/repos.d/"]
    
    type Code = {
        N: int;
        K: int;
        polys: int list
    }
    
    type BitString =
        | BitString of int list
    
    let bsToS (BitString bs) = 
        let folder (sb:StringBuilder) c = sb.Append(if c=1 then '0' else '1')
        List.fold folder (new StringBuilder()) bs
        |> string
    
    let sToBS s =
        BitString [for c in s -> if c='1' then 1 else 0]
    
    
    let readCodeConfig () : Code =
        let N, K =
            Console.ReadLine().Split ' '
            |> Array.map int
            |> (fun arr -> arr.[0], arr.[1])
          
        let polys =  
            Seq.init N (fun _ -> Console.ReadLine())
            |> Seq.map (fun s -> new string(s.ToCharArray() |> Array.rev))
            |> Seq.map (fun s -> Convert.ToInt32(s, 2))
            |> Seq.toList
        
        {N=N; K=K; polys=polys}
            
    let hammingDist a b =
        List.zip a b
        |> List.map (fun (a,b) -> a^^^b)
        |> List.fold (+) 0
            
    let rec convolve a = function
        | 0 when a=0 -> 0
        | b ->
            (a &&& b &&& 1) ^^^ convolve (a>>>1) (b>>>1)
            
    let dropLast n xs =
        List.take (List.length xs - n) xs
        
    let stateTransition K old newSymbol = 
        let stateMask = (1<<<K) - 1
        (old <<< 1) &&& stateMask ||| newSymbol
        
    
        
    let convolutionalDecode (code:Code) (BitString msg) : BitString =
        let numStates = (1<<<code.K) - 1
    
        let foldViterbi oldStates block =
            let inner state =
                let selfDist =
                    List.map (convolve state) code.polys
                    |> hammingDist block
                let zeroState = state >>> 1
                let (zeroDist, zeroPath) = List.item zeroState oldStates
                let oneState = (1 <<< (code.K-1)) + zeroState
                let (oneDist, onePath)  = List.item oneState oldStates
                if zeroDist < oneDist then
                    (selfDist + zeroDist, (state &&& 1) :: zeroPath)
                else
                    (selfDist + oneDist , (state &&& 1) :: onePath)
            
            [0..numStates]
            |> List.map inner
        
        List.chunkBySize code.N msg
        |> List.fold foldViterbi [for i in 0..numStates -> if i=0 then (0,[]) else (1000000000,[])]
        |> List.sortBy fst
        |> List.head
        |> snd
        |> List.rev
        |> dropLast code.K
        |> BitString
        
    let convolutionalEncode (code:Code) (BitString msg) : BitString =
        let padding = [for i in 1..code.K -> 0]
        let run (state, output) input = 
            let nextState = stateTransition code.K state input
            let nextOutput = List.map (convolve nextState) code.polys
            (nextState, output @ nextOutput)
        List.fold run (0, []) (msg @ padding)
        |> snd
        |> BitString
    
    let lookupMessage (BitString msg) =
        let size = 20
        let msgT = List.take (8*size) msg
    
        let ctobs c =
            let i = int c
            [for j in 7 .. -1 .. 0 -> if i&&&(1<<<j) <> 0 then 1 else 0]
        let hammingTxt t =
            List.zip (List.take (8*size) t) msgT
            |> List.map (fun (a,b) -> a ^^^ b)
            |> List.fold (+) 0
    
        List.map (fun t -> Seq.collect ctobs t |> Seq.toList) texts
        |> List.minBy hammingTxt
        |> BitString
        
    
    [<EntryPoint>]
    let main argv =
        let codeA = readCodeConfig()
        let codeB = readCodeConfig()
        let msg =
            Seq.initInfinite (fun _ -> Console.ReadLine())
            |> Seq.takeWhile (fun x -> x <> null)
            |> String.concat ""
            |> sToBS
    
        convolutionalDecode codeA msg
        |> lookupMessage
        |> convolutionalEncode codeB
        |> bsToS
        |> Console.WriteLine
        0
    

    use with f#

  • + 0 comments

    Claude Shannon's smart ideas helped us with a cool coding challenge on our site! We used convolutional codes, like Voyager's (2, 7) and Pathfinder's (6, 15), to make sending messages more reliable. Big thanks to Elias for his awesome help on our website!