Instruction
stringlengths
45
106
input_code
stringlengths
1
13.7k
output_code
stringlengths
1
13.7k
Produce a language-to-language conversion: from Haskell to Go, same semantics.
import System.IO import MorseCode import MorsePlaySox main = do hSetBuffering stdin NoBuffering text <- getContents play $ toMorse text
package main import ( "flag" "fmt" "log" "regexp" "strings" "syscall" "time" "unicode" ) type key struct { duration int on bool sym string } var ( runeToKeys = map[rune][]key{} interCharGap = []key{{1, false, ""}} punctGap = []key{{7, false, " / "}} charGap = []key{{3, false, " "}} wordGap = []key{{7, false, " / "}} ) const rawMorse = ` A:.- J:.--- S:... 1:.---- .:.-.-.-  ::---... B:-... K:-.- T:- 2:..--- ,:--..--  ;:-.-.-. C:-.-. L:.-.. U:..- 3:...--  ?:..--.. =:-...- D:-.. M:-- V:...- 4:....- ':.----. +:.-.-. E:. N:-. W:.-- 5:.....  !:-.-.-- -:-....- F:..-. O:--- X:-..- 6:-.... /:-..-. _:..--.- G:--. P:.--. Y:-.-- 7:--... (:-.--. ":.-..-. H:.... Q:--.- Z:--.. 8:---.. ):-.--.- $:...-..- I:.. R:.-. 0:----- 9:----. &:.-... @:.--.-. ` func init() { r := regexp.MustCompile("([^ ]):([.-]+)") for _, m := range r.FindAllStringSubmatch(rawMorse, -1) { c := m[1][0] keys := []key{} for i, dd := range m[2] { if i > 0 { keys = append(keys, interCharGap...) } if dd == '.' { keys = append(keys, key{1, true, "."}) } else if dd == '-' { keys = append(keys, key{3, true, "-"}) } else { log.Fatalf("found %c in morse for %c", dd, c) } runeToKeys[rune(c)] = keys runeToKeys[unicode.ToLower(rune(c))] = keys } } } func MorseKeys(in string) ([]key, error) { afterWord := false afterChar := false result := []key{} for _, c := range in { if unicode.IsSpace(c) { afterWord = true continue } morse, ok := runeToKeys[c] if !ok { return nil, fmt.Errorf("can't translate %c to morse", c) } if unicode.IsPunct(c) && afterChar { result = append(result, punctGap...) } else if afterWord { result = append(result, wordGap...) } else if afterChar { result = append(result, charGap...) } result = append(result, morse...) afterChar = true afterWord = false } return result, nil } func main() { var ditDuration time.Duration flag.DurationVar(&ditDuration, "d", 40*time.Millisecond, "length of dit") flag.Parse() in := "hello world." if len(flag.Args()) > 1 { in = strings.Join(flag.Args(), " ") } keys, err := MorseKeys(in) if err != nil { log.Fatalf("failed to translate: %s", err) } for _, k := range keys { if k.on { if err := note(true); err != nil { log.Fatalf("failed to play note: %s", err) } } fmt.Print(k.sym) time.Sleep(ditDuration * time.Duration(k.duration)) if k.on { if err := note(false); err != nil { log.Fatalf("failed to stop note: %s", err) } } } fmt.Println() } var consoleFD uintptr func init() { fd, err := syscall.Open("/dev/console", syscall.O_WRONLY, 0) if err != nil { log.Fatalf("failed to get console device: %s", err) } consoleFD = uintptr(fd) } const KIOCSOUND = 0x4B2F const clockTickRate = 1193180 const freqHz = 600 func note(on bool) error { arg := uintptr(0) if on { arg = clockTickRate / freqHz } _, _, errno := syscall.Syscall(syscall.SYS_IOCTL, consoleFD, KIOCSOUND, arg) if errno != 0 { return errno } return nil }
Convert the following code from J to C, ensuring the logic remains intact.
require'strings media/wav' morse=:[:; [:(' ',~' .-' {~ 3&#.inv)&.> (_96{.".0 :0-.LF) {~ a.&i.@toupper 79 448 0 1121 0 0 484 214 644 0 151 692 608 455 205 242 161 134 125 122 121 202 229 238 241 715 637 0 203 0 400 475 5 67 70 22 1 43 25 40 4 53 23 49 8 7 26 52 77 16 13 2 14 41 17 68 71 76 214 0 644 0 401 ) onoffdur=: 0.01*100<.@*(1.2%[)*(4 4#:2 5 13){~' .-'i.] playmorse=: 30&$: :((wavnote&, 63 __"1)@(onoffdur morse))
#include <ctype.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #define BIND(A,L,H) ((L)<(A)?(A)<(H)?(A):(H):(L)) char dih[50],dah[50],medium[30],word[30], *dd[2] = {dih,dah}; const char *ascii = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789.,?'!/()&:;=+-_\"$@", *itu[] = { "13","3111","3131","311","1","1131","331","1111","11","1333","313","1311","33","31","333","1331","3313","131","111","3","113","1113","133","3113","3133","3311","33333","13333","11333","11133","11113","11111","31111","33111","33311","33331","131313","331133","113311","133331","313133","31131","31331","313313","13111","333111","313131","31113","13131","311113","113313","131131","1113113","133131" }; void append(char*s,const char*morse) { for (; *morse; ++morse) strcat(s,dd['3'==*morse]); strcat(s,medium); } char*translate(const char*i,char*o) { const char*pc; sprintf(o,"beep"); for (; *i; ++i) if (NULL == (pc = strchr(ascii,toupper(*i)))) strcat(o,word); else append(o,itu[pc-ascii]); strcat(o,word); return o; } int main(int ac,char*av[]) { char sin[73],sout[100000]; int dit = 100; if (1 < ac) { if (strlen(av[1]) != strspn(av[1],"0123456789")) return 0*fprintf(stderr,"use: %s [duration] dit in ms, default %d\n",*av,dit); dit = BIND(atoi(av[1]),1,1000); } sprintf(dah," -n -f 440 -l %d -D %d",3*dit,dit); sprintf(dih," -n -f 440 -l %d -D %d",dit,dit); sprintf(medium," -n -D %d",(3-1)*dit); sprintf(word," -n -D %d",(7-(3-1)-1)*dit); while (NULL != fgets(sin,72,stdin)) puts(translate(sin,sout)); return 0; }
Translate this program into C# but keep the logic exactly as in J.
require'strings media/wav' morse=:[:; [:(' ',~' .-' {~ 3&#.inv)&.> (_96{.".0 :0-.LF) {~ a.&i.@toupper 79 448 0 1121 0 0 484 214 644 0 151 692 608 455 205 242 161 134 125 122 121 202 229 238 241 715 637 0 203 0 400 475 5 67 70 22 1 43 25 40 4 53 23 49 8 7 26 52 77 16 13 2 14 41 17 68 71 76 214 0 644 0 401 ) onoffdur=: 0.01*100<.@*(1.2%[)*(4 4#:2 5 13){~' .-'i.] playmorse=: 30&$: :((wavnote&, 63 __"1)@(onoffdur morse))
using System; using System.Collections.Generic; namespace Morse { class Morse { static void Main(string[] args) { string word = "sos"; Dictionary<string, string> Codes = new Dictionary<string, string> { {"a", ".- "}, {"b", "-... "}, {"c", "-.-. "}, {"d", "-.. "}, {"e", ". "}, {"f", "..-. "}, {"g", "--. "}, {"h", ".... "}, {"i", ".. "}, {"j", ".--- "}, {"k", "-.- "}, {"l", ".-.. "}, {"m", "-- "}, {"n", "-. "}, {"o", "--- "}, {"p", ".--. "}, {"q", "--.- "}, {"r", ".-. "}, {"s", "... "}, {"t", "- "}, {"u", "..- "}, {"v", "...- "}, {"w", ".-- "}, {"x", "-..- "}, {"y", "-.-- "}, {"z", "--.. "}, {"0", "-----"}, {"1", ".----"}, {"2", "..---"}, {"3", "...--"}, {"4", "....-"}, {"5", "....."}, {"6", "-...."}, {"7", "--..."}, {"8", "---.."}, {"9", "----."} }; foreach (char c in word.ToCharArray()) { string rslt = Codes[c.ToString()].Trim(); foreach (char c2 in rslt.ToCharArray()) { if (c2 == '.') Console.Beep(1000, 250); else Console.Beep(1000, 750); } System.Threading.Thread.Sleep(50); } } } }
Convert this J block to Java, preserving its control flow and logic.
require'strings media/wav' morse=:[:; [:(' ',~' .-' {~ 3&#.inv)&.> (_96{.".0 :0-.LF) {~ a.&i.@toupper 79 448 0 1121 0 0 484 214 644 0 151 692 608 455 205 242 161 134 125 122 121 202 229 238 241 715 637 0 203 0 400 475 5 67 70 22 1 43 25 40 4 53 23 49 8 7 26 52 77 16 13 2 14 41 17 68 71 76 214 0 644 0 401 ) onoffdur=: 0.01*100<.@*(1.2%[)*(4 4#:2 5 13){~' .-'i.] playmorse=: 30&$: :((wavnote&, 63 __"1)@(onoffdur morse))
import java.util.*; public class MorseCode { final static String[][] code = { {"A", ".- "}, {"B", "-... "}, {"C", "-.-. "}, {"D", "-.. "}, {"E", ". "}, {"F", "..-. "}, {"G", "--. "}, {"H", ".... "}, {"I", ".. "}, {"J", ".--- "}, {"K", "-.- "}, {"L", ".-.. "}, {"M", "-- "}, {"N", "-. "}, {"O", "--- "}, {"P", ".--. "}, {"Q", "--.- "}, {"R", ".-. "}, {"S", "... "}, {"T", "- "}, {"U", "..- "}, {"V", "...- "}, {"W", ".- - "}, {"X", "-..- "}, {"Y", "-.-- "}, {"Z", "--.. "}, {"0", "----- "}, {"1", ".---- "}, {"2", "..--- "}, {"3", "...-- "}, {"4", "....- "}, {"5", "..... "}, {"6", "-.... "}, {"7", "--... "}, {"8", "---.. "}, {"9", "----. "}, {"'", ".----. "}, {":", "---... "}, {",", "--..-- "}, {"-", "-....- "}, {"(", "-.--.- "}, {".", ".-.-.- "}, {"?", "..--.. "}, {";", "-.-.-. "}, {"/", "-..-. "}, {"-", "..--.- "}, {")", "---.. "}, {"=", "-...- "}, {"@", ".--.-. "}, {"\"", ".-..-."}, {"+", ".-.-. "}, {" ", "/"}}; final static Map<Character, String> map = new HashMap<>(); static { for (String[] pair : code) map.put(pair[0].charAt(0), pair[1].trim()); } public static void main(String[] args) { printMorse("sos"); printMorse(" Hello World!"); printMorse("Rosetta Code"); } static void printMorse(String input) { System.out.printf("%s %n", input); input = input.trim().replaceAll("[ ]+", " ").toUpperCase(); for (char c : input.toCharArray()) { String s = map.get(c); if (s != null) System.out.printf("%s ", s); } System.out.println("\n"); } }
Write the same code in Python as shown below in J.
require'strings media/wav' morse=:[:; [:(' ',~' .-' {~ 3&#.inv)&.> (_96{.".0 :0-.LF) {~ a.&i.@toupper 79 448 0 1121 0 0 484 214 644 0 151 692 608 455 205 242 161 134 125 122 121 202 229 238 241 715 637 0 203 0 400 475 5 67 70 22 1 43 25 40 4 53 23 49 8 7 26 52 77 16 13 2 14 41 17 68 71 76 214 0 644 0 401 ) onoffdur=: 0.01*100<.@*(1.2%[)*(4 4#:2 5 13){~' .-'i.] playmorse=: 30&$: :((wavnote&, 63 __"1)@(onoffdur morse))
import time, winsound char2morse = { "!": "---.", "\"": ".-..-.", "$": "...-..-", "'": ".----.", "(": "-.--.", ")": "-.--.-", "+": ".-.-.", ",": "--..--", "-": "-....-", ".": ".-.-.-", "/": "-..-.", "0": "-----", "1": ".----", "2": "..---", "3": "...--", "4": "....-", "5": ".....", "6": "-....", "7": "--...", "8": "---..", "9": "----.", ":": "---...", ";": "-.-.-.", "=": "-...-", "?": "..--..", "@": ".--.-.", "A": ".-", "B": "-...", "C": "-.-.", "D": "-..", "E": ".", "F": "..-.", "G": "--.", "H": "....", "I": "..", "J": ".---", "K": "-.-", "L": ".-..", "M": "--", "N": "-.", "O": "---", "P": ".--.", "Q": "--.-", "R": ".-.", "S": "...", "T": "-", "U": "..-", "V": "...-", "W": ".--", "X": "-..-", "Y": "-.--", "Z": "--..", "[": "-.--.", "]": "-.--.-", "_": "..--.-", } e = 50 f = 1280 chargap = 1 wordgap = 7 def gap(n=1): time.sleep(n * e / 1000) off = gap def on(n=1): winsound.Beep(f, n * e) def dit(): on(); off() def dah(): on(3); off() def bloop(n=3): winsound.Beep(f//2, n * e) def windowsmorse(text): for word in text.strip().upper().split(): for char in word: for element in char2morse.get(char, '?'): if element == '-': dah() elif element == '.': dit() else: bloop() gap(chargap) gap(wordgap) while True: windowsmorse(input('A string to change into morse: '))
Transform the following J implementation into VB, maintaining the same output and logic.
require'strings media/wav' morse=:[:; [:(' ',~' .-' {~ 3&#.inv)&.> (_96{.".0 :0-.LF) {~ a.&i.@toupper 79 448 0 1121 0 0 484 214 644 0 151 692 608 455 205 242 161 134 125 122 121 202 229 238 241 715 637 0 203 0 400 475 5 67 70 22 1 43 25 40 4 53 23 49 8 7 26 52 77 16 13 2 14 41 17 68 71 76 214 0 644 0 401 ) onoffdur=: 0.01*100<.@*(1.2%[)*(4 4#:2 5 13){~' .-'i.] playmorse=: 30&$: :((wavnote&, 63 __"1)@(onoffdur morse))
Option Explicit Private Declare Function Beep Lib "kernel32" (ByVal dwFreq As Long, ByVal dwDuration As Long) As Long Private Declare Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As Long) Private Const MORSE_ALPHA As String = ".-,-...,-.-.,-..,.,..-.,--.,....,..,.---,-.-,.-..,--,-.,---,.--.,--.-,.-.,...,-,..-,...-,.--,-..-,-.--,--.." Private Const MORSE_NUMERIC As String = "-----,.----,..---,...--,....-,.....,-....,--...,---..,----." Private Const ONE_UNIT As Integer = 100 Private Const BEEP_DOT As Integer = ONE_UNIT Private Const BEEP_DASH As Integer = 3 * ONE_UNIT Private Const BEEP_OTHER As Integer = 7 * ONE_UNIT Private Const DELAY As Integer = ONE_UNIT Private Const LETTERS_DELAY As Integer = 3 * ONE_UNIT Private Const SPACE_DELAY As Integer = 7 * ONE_UNIT Private Const FREQUENCY_CHARS As Integer = 1200 Private Const FREQUENCY_OTHERCHARS As Integer = 400 Sub Main() Dim p$, temp$ p = ToMorse("Hel/lo 123 world") temp = Replace(p, "+", "") Debug.Print Replace(temp, "_", "") PlayMorse p End Sub Private Function ToMorse(s As String) As String Dim i&, t$, j& s = UCase(s) For i = 1 To Len(s) j = Asc(Mid(s, i, 1)) Select Case j Case 65 To 90 t = t & Split(MORSE_ALPHA, ",")(j - 65) & "+" Case 48 To 57 t = t & Split(MORSE_NUMERIC, ",")(j - 48) & "+" Case 32 t = t & " " & "+" Case Else t = t & "_" & "+" End Select Next i ToMorse = t End Function Private Sub PlayMorse(s As String) Dim i& For i = 1 To Len(s) Select Case Mid(s, i, 1) Case ".": Beep FREQUENCY_CHARS, BEEP_DOT Case "-": Beep FREQUENCY_CHARS, BEEP_DASH Case "_": Beep FREQUENCY_OTHERCHARS, BEEP_OTHER Case "+": Sleep LETTERS_DELAY Case " ": Sleep SPACE_DELAY End Select Sleep DELAY Next i End Sub
Can you help me rewrite this code in Go instead of J, keeping it the same logically?
require'strings media/wav' morse=:[:; [:(' ',~' .-' {~ 3&#.inv)&.> (_96{.".0 :0-.LF) {~ a.&i.@toupper 79 448 0 1121 0 0 484 214 644 0 151 692 608 455 205 242 161 134 125 122 121 202 229 238 241 715 637 0 203 0 400 475 5 67 70 22 1 43 25 40 4 53 23 49 8 7 26 52 77 16 13 2 14 41 17 68 71 76 214 0 644 0 401 ) onoffdur=: 0.01*100<.@*(1.2%[)*(4 4#:2 5 13){~' .-'i.] playmorse=: 30&$: :((wavnote&, 63 __"1)@(onoffdur morse))
package main import ( "flag" "fmt" "log" "regexp" "strings" "syscall" "time" "unicode" ) type key struct { duration int on bool sym string } var ( runeToKeys = map[rune][]key{} interCharGap = []key{{1, false, ""}} punctGap = []key{{7, false, " / "}} charGap = []key{{3, false, " "}} wordGap = []key{{7, false, " / "}} ) const rawMorse = ` A:.- J:.--- S:... 1:.---- .:.-.-.-  ::---... B:-... K:-.- T:- 2:..--- ,:--..--  ;:-.-.-. C:-.-. L:.-.. U:..- 3:...--  ?:..--.. =:-...- D:-.. M:-- V:...- 4:....- ':.----. +:.-.-. E:. N:-. W:.-- 5:.....  !:-.-.-- -:-....- F:..-. O:--- X:-..- 6:-.... /:-..-. _:..--.- G:--. P:.--. Y:-.-- 7:--... (:-.--. ":.-..-. H:.... Q:--.- Z:--.. 8:---.. ):-.--.- $:...-..- I:.. R:.-. 0:----- 9:----. &:.-... @:.--.-. ` func init() { r := regexp.MustCompile("([^ ]):([.-]+)") for _, m := range r.FindAllStringSubmatch(rawMorse, -1) { c := m[1][0] keys := []key{} for i, dd := range m[2] { if i > 0 { keys = append(keys, interCharGap...) } if dd == '.' { keys = append(keys, key{1, true, "."}) } else if dd == '-' { keys = append(keys, key{3, true, "-"}) } else { log.Fatalf("found %c in morse for %c", dd, c) } runeToKeys[rune(c)] = keys runeToKeys[unicode.ToLower(rune(c))] = keys } } } func MorseKeys(in string) ([]key, error) { afterWord := false afterChar := false result := []key{} for _, c := range in { if unicode.IsSpace(c) { afterWord = true continue } morse, ok := runeToKeys[c] if !ok { return nil, fmt.Errorf("can't translate %c to morse", c) } if unicode.IsPunct(c) && afterChar { result = append(result, punctGap...) } else if afterWord { result = append(result, wordGap...) } else if afterChar { result = append(result, charGap...) } result = append(result, morse...) afterChar = true afterWord = false } return result, nil } func main() { var ditDuration time.Duration flag.DurationVar(&ditDuration, "d", 40*time.Millisecond, "length of dit") flag.Parse() in := "hello world." if len(flag.Args()) > 1 { in = strings.Join(flag.Args(), " ") } keys, err := MorseKeys(in) if err != nil { log.Fatalf("failed to translate: %s", err) } for _, k := range keys { if k.on { if err := note(true); err != nil { log.Fatalf("failed to play note: %s", err) } } fmt.Print(k.sym) time.Sleep(ditDuration * time.Duration(k.duration)) if k.on { if err := note(false); err != nil { log.Fatalf("failed to stop note: %s", err) } } } fmt.Println() } var consoleFD uintptr func init() { fd, err := syscall.Open("/dev/console", syscall.O_WRONLY, 0) if err != nil { log.Fatalf("failed to get console device: %s", err) } consoleFD = uintptr(fd) } const KIOCSOUND = 0x4B2F const clockTickRate = 1193180 const freqHz = 600 func note(on bool) error { arg := uintptr(0) if on { arg = clockTickRate / freqHz } _, _, errno := syscall.Syscall(syscall.SYS_IOCTL, consoleFD, KIOCSOUND, arg) if errno != 0 { return errno } return nil }
Maintain the same structure and functionality when rewriting this code in C.
using PortAudio const pstream = PortAudioStream(0, 2) sendmorsesound(t, f) = write(pstream, SinSource(eltype(stream), samplerate(stream)*0.8, [f]), (t/1000)s) char2morse = Dict[ "!" => "---.", "\"" => ".-..-.", "$" => "...-..-", "'" => ".----.", "(" => "-.--.", ")" => "-.--.-", "+" => ".-.-.", "," => "--..--", "-" => "-....-", "." => ".-.-.-", "/" => "-..-.", "0" => "-----", "1" => ".----", "2" => "..---", "3" => "...--", "4" => "....-", "5" => ".....", "6" => "-....", "7" => "--...", "8" => "---..", "9" => "----.", ":" => "---...", ";" => "-.-.-.", "=" => "-...-", "?" => "..--..", "@" => ".--.-.", "A" => ".-", "B" => "-...", "C" => "-.-.", "D" => "-..", "E" => ".", "F" => "..-.", "G" => "--.", "H" => "....", "I" => "..", "J" => ".---", "K" => "-.-", "L" => ".-..", "M" => "--", "N" => "-.", "O" => "---", "P" => ".--.", "Q" => "--.-", "R" => ".-.", "S" => "...", "T" => "-", "U" => "..-", "V" => "...-", "W" => ".--", "X" => "-..-", "Y" => "-.--", "Z" => "--..", "[" => "-.--.", "]" => "-.--.-", "_" => "..--.-"] function sendmorsesound(freq, duration) cpause() = sleep(0.080) wpause = sleep(0.400) dit() = sendmorsesound(0.070, 700) dash() = sensmorsesound(0.210, 700) sendmorsechar(c) = for d in char2morse(c) d == '.' ? dit(): dash() end end sendmorseword(w) = for c in w sendmorsechar(c) cpause() end wpause() end sendmorse(msg) = for word in uppercase(msg) sendmorseword(word) end sendmorse("sos sos sos") sendmorse("The case of letters in Morse coding is ignored."
#include <ctype.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #define BIND(A,L,H) ((L)<(A)?(A)<(H)?(A):(H):(L)) char dih[50],dah[50],medium[30],word[30], *dd[2] = {dih,dah}; const char *ascii = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789.,?'!/()&:;=+-_\"$@", *itu[] = { "13","3111","3131","311","1","1131","331","1111","11","1333","313","1311","33","31","333","1331","3313","131","111","3","113","1113","133","3113","3133","3311","33333","13333","11333","11133","11113","11111","31111","33111","33311","33331","131313","331133","113311","133331","313133","31131","31331","313313","13111","333111","313131","31113","13131","311113","113313","131131","1113113","133131" }; void append(char*s,const char*morse) { for (; *morse; ++morse) strcat(s,dd['3'==*morse]); strcat(s,medium); } char*translate(const char*i,char*o) { const char*pc; sprintf(o,"beep"); for (; *i; ++i) if (NULL == (pc = strchr(ascii,toupper(*i)))) strcat(o,word); else append(o,itu[pc-ascii]); strcat(o,word); return o; } int main(int ac,char*av[]) { char sin[73],sout[100000]; int dit = 100; if (1 < ac) { if (strlen(av[1]) != strspn(av[1],"0123456789")) return 0*fprintf(stderr,"use: %s [duration] dit in ms, default %d\n",*av,dit); dit = BIND(atoi(av[1]),1,1000); } sprintf(dah," -n -f 440 -l %d -D %d",3*dit,dit); sprintf(dih," -n -f 440 -l %d -D %d",dit,dit); sprintf(medium," -n -D %d",(3-1)*dit); sprintf(word," -n -D %d",(7-(3-1)-1)*dit); while (NULL != fgets(sin,72,stdin)) puts(translate(sin,sout)); return 0; }
Write a version of this Julia function in C# with identical behavior.
using PortAudio const pstream = PortAudioStream(0, 2) sendmorsesound(t, f) = write(pstream, SinSource(eltype(stream), samplerate(stream)*0.8, [f]), (t/1000)s) char2morse = Dict[ "!" => "---.", "\"" => ".-..-.", "$" => "...-..-", "'" => ".----.", "(" => "-.--.", ")" => "-.--.-", "+" => ".-.-.", "," => "--..--", "-" => "-....-", "." => ".-.-.-", "/" => "-..-.", "0" => "-----", "1" => ".----", "2" => "..---", "3" => "...--", "4" => "....-", "5" => ".....", "6" => "-....", "7" => "--...", "8" => "---..", "9" => "----.", ":" => "---...", ";" => "-.-.-.", "=" => "-...-", "?" => "..--..", "@" => ".--.-.", "A" => ".-", "B" => "-...", "C" => "-.-.", "D" => "-..", "E" => ".", "F" => "..-.", "G" => "--.", "H" => "....", "I" => "..", "J" => ".---", "K" => "-.-", "L" => ".-..", "M" => "--", "N" => "-.", "O" => "---", "P" => ".--.", "Q" => "--.-", "R" => ".-.", "S" => "...", "T" => "-", "U" => "..-", "V" => "...-", "W" => ".--", "X" => "-..-", "Y" => "-.--", "Z" => "--..", "[" => "-.--.", "]" => "-.--.-", "_" => "..--.-"] function sendmorsesound(freq, duration) cpause() = sleep(0.080) wpause = sleep(0.400) dit() = sendmorsesound(0.070, 700) dash() = sensmorsesound(0.210, 700) sendmorsechar(c) = for d in char2morse(c) d == '.' ? dit(): dash() end end sendmorseword(w) = for c in w sendmorsechar(c) cpause() end wpause() end sendmorse(msg) = for word in uppercase(msg) sendmorseword(word) end sendmorse("sos sos sos") sendmorse("The case of letters in Morse coding is ignored."
using System; using System.Collections.Generic; namespace Morse { class Morse { static void Main(string[] args) { string word = "sos"; Dictionary<string, string> Codes = new Dictionary<string, string> { {"a", ".- "}, {"b", "-... "}, {"c", "-.-. "}, {"d", "-.. "}, {"e", ". "}, {"f", "..-. "}, {"g", "--. "}, {"h", ".... "}, {"i", ".. "}, {"j", ".--- "}, {"k", "-.- "}, {"l", ".-.. "}, {"m", "-- "}, {"n", "-. "}, {"o", "--- "}, {"p", ".--. "}, {"q", "--.- "}, {"r", ".-. "}, {"s", "... "}, {"t", "- "}, {"u", "..- "}, {"v", "...- "}, {"w", ".-- "}, {"x", "-..- "}, {"y", "-.-- "}, {"z", "--.. "}, {"0", "-----"}, {"1", ".----"}, {"2", "..---"}, {"3", "...--"}, {"4", "....-"}, {"5", "....."}, {"6", "-...."}, {"7", "--..."}, {"8", "---.."}, {"9", "----."} }; foreach (char c in word.ToCharArray()) { string rslt = Codes[c.ToString()].Trim(); foreach (char c2 in rslt.ToCharArray()) { if (c2 == '.') Console.Beep(1000, 250); else Console.Beep(1000, 750); } System.Threading.Thread.Sleep(50); } } } }
Maintain the same structure and functionality when rewriting this code in Java.
using PortAudio const pstream = PortAudioStream(0, 2) sendmorsesound(t, f) = write(pstream, SinSource(eltype(stream), samplerate(stream)*0.8, [f]), (t/1000)s) char2morse = Dict[ "!" => "---.", "\"" => ".-..-.", "$" => "...-..-", "'" => ".----.", "(" => "-.--.", ")" => "-.--.-", "+" => ".-.-.", "," => "--..--", "-" => "-....-", "." => ".-.-.-", "/" => "-..-.", "0" => "-----", "1" => ".----", "2" => "..---", "3" => "...--", "4" => "....-", "5" => ".....", "6" => "-....", "7" => "--...", "8" => "---..", "9" => "----.", ":" => "---...", ";" => "-.-.-.", "=" => "-...-", "?" => "..--..", "@" => ".--.-.", "A" => ".-", "B" => "-...", "C" => "-.-.", "D" => "-..", "E" => ".", "F" => "..-.", "G" => "--.", "H" => "....", "I" => "..", "J" => ".---", "K" => "-.-", "L" => ".-..", "M" => "--", "N" => "-.", "O" => "---", "P" => ".--.", "Q" => "--.-", "R" => ".-.", "S" => "...", "T" => "-", "U" => "..-", "V" => "...-", "W" => ".--", "X" => "-..-", "Y" => "-.--", "Z" => "--..", "[" => "-.--.", "]" => "-.--.-", "_" => "..--.-"] function sendmorsesound(freq, duration) cpause() = sleep(0.080) wpause = sleep(0.400) dit() = sendmorsesound(0.070, 700) dash() = sensmorsesound(0.210, 700) sendmorsechar(c) = for d in char2morse(c) d == '.' ? dit(): dash() end end sendmorseword(w) = for c in w sendmorsechar(c) cpause() end wpause() end sendmorse(msg) = for word in uppercase(msg) sendmorseword(word) end sendmorse("sos sos sos") sendmorse("The case of letters in Morse coding is ignored."
import java.util.*; public class MorseCode { final static String[][] code = { {"A", ".- "}, {"B", "-... "}, {"C", "-.-. "}, {"D", "-.. "}, {"E", ". "}, {"F", "..-. "}, {"G", "--. "}, {"H", ".... "}, {"I", ".. "}, {"J", ".--- "}, {"K", "-.- "}, {"L", ".-.. "}, {"M", "-- "}, {"N", "-. "}, {"O", "--- "}, {"P", ".--. "}, {"Q", "--.- "}, {"R", ".-. "}, {"S", "... "}, {"T", "- "}, {"U", "..- "}, {"V", "...- "}, {"W", ".- - "}, {"X", "-..- "}, {"Y", "-.-- "}, {"Z", "--.. "}, {"0", "----- "}, {"1", ".---- "}, {"2", "..--- "}, {"3", "...-- "}, {"4", "....- "}, {"5", "..... "}, {"6", "-.... "}, {"7", "--... "}, {"8", "---.. "}, {"9", "----. "}, {"'", ".----. "}, {":", "---... "}, {",", "--..-- "}, {"-", "-....- "}, {"(", "-.--.- "}, {".", ".-.-.- "}, {"?", "..--.. "}, {";", "-.-.-. "}, {"/", "-..-. "}, {"-", "..--.- "}, {")", "---.. "}, {"=", "-...- "}, {"@", ".--.-. "}, {"\"", ".-..-."}, {"+", ".-.-. "}, {" ", "/"}}; final static Map<Character, String> map = new HashMap<>(); static { for (String[] pair : code) map.put(pair[0].charAt(0), pair[1].trim()); } public static void main(String[] args) { printMorse("sos"); printMorse(" Hello World!"); printMorse("Rosetta Code"); } static void printMorse(String input) { System.out.printf("%s %n", input); input = input.trim().replaceAll("[ ]+", " ").toUpperCase(); for (char c : input.toCharArray()) { String s = map.get(c); if (s != null) System.out.printf("%s ", s); } System.out.println("\n"); } }
Convert this Julia block to Python, preserving its control flow and logic.
using PortAudio const pstream = PortAudioStream(0, 2) sendmorsesound(t, f) = write(pstream, SinSource(eltype(stream), samplerate(stream)*0.8, [f]), (t/1000)s) char2morse = Dict[ "!" => "---.", "\"" => ".-..-.", "$" => "...-..-", "'" => ".----.", "(" => "-.--.", ")" => "-.--.-", "+" => ".-.-.", "," => "--..--", "-" => "-....-", "." => ".-.-.-", "/" => "-..-.", "0" => "-----", "1" => ".----", "2" => "..---", "3" => "...--", "4" => "....-", "5" => ".....", "6" => "-....", "7" => "--...", "8" => "---..", "9" => "----.", ":" => "---...", ";" => "-.-.-.", "=" => "-...-", "?" => "..--..", "@" => ".--.-.", "A" => ".-", "B" => "-...", "C" => "-.-.", "D" => "-..", "E" => ".", "F" => "..-.", "G" => "--.", "H" => "....", "I" => "..", "J" => ".---", "K" => "-.-", "L" => ".-..", "M" => "--", "N" => "-.", "O" => "---", "P" => ".--.", "Q" => "--.-", "R" => ".-.", "S" => "...", "T" => "-", "U" => "..-", "V" => "...-", "W" => ".--", "X" => "-..-", "Y" => "-.--", "Z" => "--..", "[" => "-.--.", "]" => "-.--.-", "_" => "..--.-"] function sendmorsesound(freq, duration) cpause() = sleep(0.080) wpause = sleep(0.400) dit() = sendmorsesound(0.070, 700) dash() = sensmorsesound(0.210, 700) sendmorsechar(c) = for d in char2morse(c) d == '.' ? dit(): dash() end end sendmorseword(w) = for c in w sendmorsechar(c) cpause() end wpause() end sendmorse(msg) = for word in uppercase(msg) sendmorseword(word) end sendmorse("sos sos sos") sendmorse("The case of letters in Morse coding is ignored."
import time, winsound char2morse = { "!": "---.", "\"": ".-..-.", "$": "...-..-", "'": ".----.", "(": "-.--.", ")": "-.--.-", "+": ".-.-.", ",": "--..--", "-": "-....-", ".": ".-.-.-", "/": "-..-.", "0": "-----", "1": ".----", "2": "..---", "3": "...--", "4": "....-", "5": ".....", "6": "-....", "7": "--...", "8": "---..", "9": "----.", ":": "---...", ";": "-.-.-.", "=": "-...-", "?": "..--..", "@": ".--.-.", "A": ".-", "B": "-...", "C": "-.-.", "D": "-..", "E": ".", "F": "..-.", "G": "--.", "H": "....", "I": "..", "J": ".---", "K": "-.-", "L": ".-..", "M": "--", "N": "-.", "O": "---", "P": ".--.", "Q": "--.-", "R": ".-.", "S": "...", "T": "-", "U": "..-", "V": "...-", "W": ".--", "X": "-..-", "Y": "-.--", "Z": "--..", "[": "-.--.", "]": "-.--.-", "_": "..--.-", } e = 50 f = 1280 chargap = 1 wordgap = 7 def gap(n=1): time.sleep(n * e / 1000) off = gap def on(n=1): winsound.Beep(f, n * e) def dit(): on(); off() def dah(): on(3); off() def bloop(n=3): winsound.Beep(f//2, n * e) def windowsmorse(text): for word in text.strip().upper().split(): for char in word: for element in char2morse.get(char, '?'): if element == '-': dah() elif element == '.': dit() else: bloop() gap(chargap) gap(wordgap) while True: windowsmorse(input('A string to change into morse: '))
Can you help me rewrite this code in VB instead of Julia, keeping it the same logically?
using PortAudio const pstream = PortAudioStream(0, 2) sendmorsesound(t, f) = write(pstream, SinSource(eltype(stream), samplerate(stream)*0.8, [f]), (t/1000)s) char2morse = Dict[ "!" => "---.", "\"" => ".-..-.", "$" => "...-..-", "'" => ".----.", "(" => "-.--.", ")" => "-.--.-", "+" => ".-.-.", "," => "--..--", "-" => "-....-", "." => ".-.-.-", "/" => "-..-.", "0" => "-----", "1" => ".----", "2" => "..---", "3" => "...--", "4" => "....-", "5" => ".....", "6" => "-....", "7" => "--...", "8" => "---..", "9" => "----.", ":" => "---...", ";" => "-.-.-.", "=" => "-...-", "?" => "..--..", "@" => ".--.-.", "A" => ".-", "B" => "-...", "C" => "-.-.", "D" => "-..", "E" => ".", "F" => "..-.", "G" => "--.", "H" => "....", "I" => "..", "J" => ".---", "K" => "-.-", "L" => ".-..", "M" => "--", "N" => "-.", "O" => "---", "P" => ".--.", "Q" => "--.-", "R" => ".-.", "S" => "...", "T" => "-", "U" => "..-", "V" => "...-", "W" => ".--", "X" => "-..-", "Y" => "-.--", "Z" => "--..", "[" => "-.--.", "]" => "-.--.-", "_" => "..--.-"] function sendmorsesound(freq, duration) cpause() = sleep(0.080) wpause = sleep(0.400) dit() = sendmorsesound(0.070, 700) dash() = sensmorsesound(0.210, 700) sendmorsechar(c) = for d in char2morse(c) d == '.' ? dit(): dash() end end sendmorseword(w) = for c in w sendmorsechar(c) cpause() end wpause() end sendmorse(msg) = for word in uppercase(msg) sendmorseword(word) end sendmorse("sos sos sos") sendmorse("The case of letters in Morse coding is ignored."
Option Explicit Private Declare Function Beep Lib "kernel32" (ByVal dwFreq As Long, ByVal dwDuration As Long) As Long Private Declare Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As Long) Private Const MORSE_ALPHA As String = ".-,-...,-.-.,-..,.,..-.,--.,....,..,.---,-.-,.-..,--,-.,---,.--.,--.-,.-.,...,-,..-,...-,.--,-..-,-.--,--.." Private Const MORSE_NUMERIC As String = "-----,.----,..---,...--,....-,.....,-....,--...,---..,----." Private Const ONE_UNIT As Integer = 100 Private Const BEEP_DOT As Integer = ONE_UNIT Private Const BEEP_DASH As Integer = 3 * ONE_UNIT Private Const BEEP_OTHER As Integer = 7 * ONE_UNIT Private Const DELAY As Integer = ONE_UNIT Private Const LETTERS_DELAY As Integer = 3 * ONE_UNIT Private Const SPACE_DELAY As Integer = 7 * ONE_UNIT Private Const FREQUENCY_CHARS As Integer = 1200 Private Const FREQUENCY_OTHERCHARS As Integer = 400 Sub Main() Dim p$, temp$ p = ToMorse("Hel/lo 123 world") temp = Replace(p, "+", "") Debug.Print Replace(temp, "_", "") PlayMorse p End Sub Private Function ToMorse(s As String) As String Dim i&, t$, j& s = UCase(s) For i = 1 To Len(s) j = Asc(Mid(s, i, 1)) Select Case j Case 65 To 90 t = t & Split(MORSE_ALPHA, ",")(j - 65) & "+" Case 48 To 57 t = t & Split(MORSE_NUMERIC, ",")(j - 48) & "+" Case 32 t = t & " " & "+" Case Else t = t & "_" & "+" End Select Next i ToMorse = t End Function Private Sub PlayMorse(s As String) Dim i& For i = 1 To Len(s) Select Case Mid(s, i, 1) Case ".": Beep FREQUENCY_CHARS, BEEP_DOT Case "-": Beep FREQUENCY_CHARS, BEEP_DASH Case "_": Beep FREQUENCY_OTHERCHARS, BEEP_OTHER Case "+": Sleep LETTERS_DELAY Case " ": Sleep SPACE_DELAY End Select Sleep DELAY Next i End Sub
Please provide an equivalent version of this Julia code in Go.
using PortAudio const pstream = PortAudioStream(0, 2) sendmorsesound(t, f) = write(pstream, SinSource(eltype(stream), samplerate(stream)*0.8, [f]), (t/1000)s) char2morse = Dict[ "!" => "---.", "\"" => ".-..-.", "$" => "...-..-", "'" => ".----.", "(" => "-.--.", ")" => "-.--.-", "+" => ".-.-.", "," => "--..--", "-" => "-....-", "." => ".-.-.-", "/" => "-..-.", "0" => "-----", "1" => ".----", "2" => "..---", "3" => "...--", "4" => "....-", "5" => ".....", "6" => "-....", "7" => "--...", "8" => "---..", "9" => "----.", ":" => "---...", ";" => "-.-.-.", "=" => "-...-", "?" => "..--..", "@" => ".--.-.", "A" => ".-", "B" => "-...", "C" => "-.-.", "D" => "-..", "E" => ".", "F" => "..-.", "G" => "--.", "H" => "....", "I" => "..", "J" => ".---", "K" => "-.-", "L" => ".-..", "M" => "--", "N" => "-.", "O" => "---", "P" => ".--.", "Q" => "--.-", "R" => ".-.", "S" => "...", "T" => "-", "U" => "..-", "V" => "...-", "W" => ".--", "X" => "-..-", "Y" => "-.--", "Z" => "--..", "[" => "-.--.", "]" => "-.--.-", "_" => "..--.-"] function sendmorsesound(freq, duration) cpause() = sleep(0.080) wpause = sleep(0.400) dit() = sendmorsesound(0.070, 700) dash() = sensmorsesound(0.210, 700) sendmorsechar(c) = for d in char2morse(c) d == '.' ? dit(): dash() end end sendmorseword(w) = for c in w sendmorsechar(c) cpause() end wpause() end sendmorse(msg) = for word in uppercase(msg) sendmorseword(word) end sendmorse("sos sos sos") sendmorse("The case of letters in Morse coding is ignored."
package main import ( "flag" "fmt" "log" "regexp" "strings" "syscall" "time" "unicode" ) type key struct { duration int on bool sym string } var ( runeToKeys = map[rune][]key{} interCharGap = []key{{1, false, ""}} punctGap = []key{{7, false, " / "}} charGap = []key{{3, false, " "}} wordGap = []key{{7, false, " / "}} ) const rawMorse = ` A:.- J:.--- S:... 1:.---- .:.-.-.-  ::---... B:-... K:-.- T:- 2:..--- ,:--..--  ;:-.-.-. C:-.-. L:.-.. U:..- 3:...--  ?:..--.. =:-...- D:-.. M:-- V:...- 4:....- ':.----. +:.-.-. E:. N:-. W:.-- 5:.....  !:-.-.-- -:-....- F:..-. O:--- X:-..- 6:-.... /:-..-. _:..--.- G:--. P:.--. Y:-.-- 7:--... (:-.--. ":.-..-. H:.... Q:--.- Z:--.. 8:---.. ):-.--.- $:...-..- I:.. R:.-. 0:----- 9:----. &:.-... @:.--.-. ` func init() { r := regexp.MustCompile("([^ ]):([.-]+)") for _, m := range r.FindAllStringSubmatch(rawMorse, -1) { c := m[1][0] keys := []key{} for i, dd := range m[2] { if i > 0 { keys = append(keys, interCharGap...) } if dd == '.' { keys = append(keys, key{1, true, "."}) } else if dd == '-' { keys = append(keys, key{3, true, "-"}) } else { log.Fatalf("found %c in morse for %c", dd, c) } runeToKeys[rune(c)] = keys runeToKeys[unicode.ToLower(rune(c))] = keys } } } func MorseKeys(in string) ([]key, error) { afterWord := false afterChar := false result := []key{} for _, c := range in { if unicode.IsSpace(c) { afterWord = true continue } morse, ok := runeToKeys[c] if !ok { return nil, fmt.Errorf("can't translate %c to morse", c) } if unicode.IsPunct(c) && afterChar { result = append(result, punctGap...) } else if afterWord { result = append(result, wordGap...) } else if afterChar { result = append(result, charGap...) } result = append(result, morse...) afterChar = true afterWord = false } return result, nil } func main() { var ditDuration time.Duration flag.DurationVar(&ditDuration, "d", 40*time.Millisecond, "length of dit") flag.Parse() in := "hello world." if len(flag.Args()) > 1 { in = strings.Join(flag.Args(), " ") } keys, err := MorseKeys(in) if err != nil { log.Fatalf("failed to translate: %s", err) } for _, k := range keys { if k.on { if err := note(true); err != nil { log.Fatalf("failed to play note: %s", err) } } fmt.Print(k.sym) time.Sleep(ditDuration * time.Duration(k.duration)) if k.on { if err := note(false); err != nil { log.Fatalf("failed to stop note: %s", err) } } } fmt.Println() } var consoleFD uintptr func init() { fd, err := syscall.Open("/dev/console", syscall.O_WRONLY, 0) if err != nil { log.Fatalf("failed to get console device: %s", err) } consoleFD = uintptr(fd) } const KIOCSOUND = 0x4B2F const clockTickRate = 1193180 const freqHz = 600 func note(on bool) error { arg := uintptr(0) if on { arg = clockTickRate / freqHz } _, _, errno := syscall.Syscall(syscall.SYS_IOCTL, consoleFD, KIOCSOUND, arg) if errno != 0 { return errno } return nil }
Keep all operations the same but rewrite the snippet in C.
local M = {} local BUZZER = pio.PB_10 local dit_length, dah_length, word_length local buzz, dah, dit, init, inter_element_gap, medium_gap, pause, sequence, short_gap buzz = function(duration) pio.pin.output(BUZZER) pio.pin.setlow(BUZZER) tmr.delay(tmr.SYS_TIMER, duration) pio.pin.sethigh(BUZZER) pio.pin.input(BUZZER) end dah = function() buzz(dah_length) end dit = function() buzz(dit_length) end init = function(baseline) dit_length = baseline dah_length = 2 * baseline word_length = 4 * baseline end inter_element_gap = function() pause(dit_length) end medium_gap = function() pause(word_length) end pause = function(duration) tmr.delay(tmr.SYS_TIMER, duration) end sequence = function(codes) if codes then for _,f in ipairs(codes) do f() inter_element_gap() end short_gap() end end short_gap = function() pause(dah_length) end local morse = { a = { dit, dah }, b = { dah, dit, dit, dit }, c = { dah, dit, dah, dit }, d = { dah, dit, dit }, e = { dit }, f = { dit, dit, dah, dit }, g = { dah, dah, dit }, h = { dit, dit, dit ,dit }, i = { dit, dit }, j = { dit, dah, dah, dah }, k = { dah, dit, dah }, l = { dit, dah, dit, dit }, m = { dah, dah }, n = { dah, dit }, o = { dah, dah, dah }, p = { dit, dah, dah, dit }, q = { dah, dah, dit, dah }, r = { dit, dah, dit }, s = { dit, dit, dit }, t = { dah }, u = { dit, dit, dah }, v = { dit, dit, dit, dah }, w = { dit, dah, dah }, x = { dah, dit, dit, dah }, y = { dah, dit, dah, dah }, z = { dah, dah, dit, dit }, ["0"] = { dah, dah, dah, dah, dah }, ["1"] = { dit, dah, dah, dah, dah }, ["2"] = { dit, dit, dah, dah, dah }, ["3"] = { dit, dit, dit, dah, dah }, ["4"] = { dit, dit, dit, dit, dah }, ["5"] = { dit, dit, dit, dit, dit }, ["6"] = { dah, dit, dit, dit, dit }, ["7"] = { dah, dah, dit, dit, dit }, ["8"] = { dah, dah, dah, dit, dit }, ["9"] = { dah, dah, dah, dah, dit }, [" "] = { medium_gap } } M.beep = function(message) message = message:lower() for _,ch in ipairs { message:byte(1, #message) } do sequence(morse[string.char(ch)]) end end M.set_dit = function(duration) init(duration) end init(50000) return M
#include <ctype.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #define BIND(A,L,H) ((L)<(A)?(A)<(H)?(A):(H):(L)) char dih[50],dah[50],medium[30],word[30], *dd[2] = {dih,dah}; const char *ascii = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789.,?'!/()&:;=+-_\"$@", *itu[] = { "13","3111","3131","311","1","1131","331","1111","11","1333","313","1311","33","31","333","1331","3313","131","111","3","113","1113","133","3113","3133","3311","33333","13333","11333","11133","11113","11111","31111","33111","33311","33331","131313","331133","113311","133331","313133","31131","31331","313313","13111","333111","313131","31113","13131","311113","113313","131131","1113113","133131" }; void append(char*s,const char*morse) { for (; *morse; ++morse) strcat(s,dd['3'==*morse]); strcat(s,medium); } char*translate(const char*i,char*o) { const char*pc; sprintf(o,"beep"); for (; *i; ++i) if (NULL == (pc = strchr(ascii,toupper(*i)))) strcat(o,word); else append(o,itu[pc-ascii]); strcat(o,word); return o; } int main(int ac,char*av[]) { char sin[73],sout[100000]; int dit = 100; if (1 < ac) { if (strlen(av[1]) != strspn(av[1],"0123456789")) return 0*fprintf(stderr,"use: %s [duration] dit in ms, default %d\n",*av,dit); dit = BIND(atoi(av[1]),1,1000); } sprintf(dah," -n -f 440 -l %d -D %d",3*dit,dit); sprintf(dih," -n -f 440 -l %d -D %d",dit,dit); sprintf(medium," -n -D %d",(3-1)*dit); sprintf(word," -n -D %d",(7-(3-1)-1)*dit); while (NULL != fgets(sin,72,stdin)) puts(translate(sin,sout)); return 0; }
Maintain the same structure and functionality when rewriting this code in C#.
local M = {} local BUZZER = pio.PB_10 local dit_length, dah_length, word_length local buzz, dah, dit, init, inter_element_gap, medium_gap, pause, sequence, short_gap buzz = function(duration) pio.pin.output(BUZZER) pio.pin.setlow(BUZZER) tmr.delay(tmr.SYS_TIMER, duration) pio.pin.sethigh(BUZZER) pio.pin.input(BUZZER) end dah = function() buzz(dah_length) end dit = function() buzz(dit_length) end init = function(baseline) dit_length = baseline dah_length = 2 * baseline word_length = 4 * baseline end inter_element_gap = function() pause(dit_length) end medium_gap = function() pause(word_length) end pause = function(duration) tmr.delay(tmr.SYS_TIMER, duration) end sequence = function(codes) if codes then for _,f in ipairs(codes) do f() inter_element_gap() end short_gap() end end short_gap = function() pause(dah_length) end local morse = { a = { dit, dah }, b = { dah, dit, dit, dit }, c = { dah, dit, dah, dit }, d = { dah, dit, dit }, e = { dit }, f = { dit, dit, dah, dit }, g = { dah, dah, dit }, h = { dit, dit, dit ,dit }, i = { dit, dit }, j = { dit, dah, dah, dah }, k = { dah, dit, dah }, l = { dit, dah, dit, dit }, m = { dah, dah }, n = { dah, dit }, o = { dah, dah, dah }, p = { dit, dah, dah, dit }, q = { dah, dah, dit, dah }, r = { dit, dah, dit }, s = { dit, dit, dit }, t = { dah }, u = { dit, dit, dah }, v = { dit, dit, dit, dah }, w = { dit, dah, dah }, x = { dah, dit, dit, dah }, y = { dah, dit, dah, dah }, z = { dah, dah, dit, dit }, ["0"] = { dah, dah, dah, dah, dah }, ["1"] = { dit, dah, dah, dah, dah }, ["2"] = { dit, dit, dah, dah, dah }, ["3"] = { dit, dit, dit, dah, dah }, ["4"] = { dit, dit, dit, dit, dah }, ["5"] = { dit, dit, dit, dit, dit }, ["6"] = { dah, dit, dit, dit, dit }, ["7"] = { dah, dah, dit, dit, dit }, ["8"] = { dah, dah, dah, dit, dit }, ["9"] = { dah, dah, dah, dah, dit }, [" "] = { medium_gap } } M.beep = function(message) message = message:lower() for _,ch in ipairs { message:byte(1, #message) } do sequence(morse[string.char(ch)]) end end M.set_dit = function(duration) init(duration) end init(50000) return M
using System; using System.Collections.Generic; namespace Morse { class Morse { static void Main(string[] args) { string word = "sos"; Dictionary<string, string> Codes = new Dictionary<string, string> { {"a", ".- "}, {"b", "-... "}, {"c", "-.-. "}, {"d", "-.. "}, {"e", ". "}, {"f", "..-. "}, {"g", "--. "}, {"h", ".... "}, {"i", ".. "}, {"j", ".--- "}, {"k", "-.- "}, {"l", ".-.. "}, {"m", "-- "}, {"n", "-. "}, {"o", "--- "}, {"p", ".--. "}, {"q", "--.- "}, {"r", ".-. "}, {"s", "... "}, {"t", "- "}, {"u", "..- "}, {"v", "...- "}, {"w", ".-- "}, {"x", "-..- "}, {"y", "-.-- "}, {"z", "--.. "}, {"0", "-----"}, {"1", ".----"}, {"2", "..---"}, {"3", "...--"}, {"4", "....-"}, {"5", "....."}, {"6", "-...."}, {"7", "--..."}, {"8", "---.."}, {"9", "----."} }; foreach (char c in word.ToCharArray()) { string rslt = Codes[c.ToString()].Trim(); foreach (char c2 in rslt.ToCharArray()) { if (c2 == '.') Console.Beep(1000, 250); else Console.Beep(1000, 750); } System.Threading.Thread.Sleep(50); } } } }
Transform the following Lua implementation into Java, maintaining the same output and logic.
local M = {} local BUZZER = pio.PB_10 local dit_length, dah_length, word_length local buzz, dah, dit, init, inter_element_gap, medium_gap, pause, sequence, short_gap buzz = function(duration) pio.pin.output(BUZZER) pio.pin.setlow(BUZZER) tmr.delay(tmr.SYS_TIMER, duration) pio.pin.sethigh(BUZZER) pio.pin.input(BUZZER) end dah = function() buzz(dah_length) end dit = function() buzz(dit_length) end init = function(baseline) dit_length = baseline dah_length = 2 * baseline word_length = 4 * baseline end inter_element_gap = function() pause(dit_length) end medium_gap = function() pause(word_length) end pause = function(duration) tmr.delay(tmr.SYS_TIMER, duration) end sequence = function(codes) if codes then for _,f in ipairs(codes) do f() inter_element_gap() end short_gap() end end short_gap = function() pause(dah_length) end local morse = { a = { dit, dah }, b = { dah, dit, dit, dit }, c = { dah, dit, dah, dit }, d = { dah, dit, dit }, e = { dit }, f = { dit, dit, dah, dit }, g = { dah, dah, dit }, h = { dit, dit, dit ,dit }, i = { dit, dit }, j = { dit, dah, dah, dah }, k = { dah, dit, dah }, l = { dit, dah, dit, dit }, m = { dah, dah }, n = { dah, dit }, o = { dah, dah, dah }, p = { dit, dah, dah, dit }, q = { dah, dah, dit, dah }, r = { dit, dah, dit }, s = { dit, dit, dit }, t = { dah }, u = { dit, dit, dah }, v = { dit, dit, dit, dah }, w = { dit, dah, dah }, x = { dah, dit, dit, dah }, y = { dah, dit, dah, dah }, z = { dah, dah, dit, dit }, ["0"] = { dah, dah, dah, dah, dah }, ["1"] = { dit, dah, dah, dah, dah }, ["2"] = { dit, dit, dah, dah, dah }, ["3"] = { dit, dit, dit, dah, dah }, ["4"] = { dit, dit, dit, dit, dah }, ["5"] = { dit, dit, dit, dit, dit }, ["6"] = { dah, dit, dit, dit, dit }, ["7"] = { dah, dah, dit, dit, dit }, ["8"] = { dah, dah, dah, dit, dit }, ["9"] = { dah, dah, dah, dah, dit }, [" "] = { medium_gap } } M.beep = function(message) message = message:lower() for _,ch in ipairs { message:byte(1, #message) } do sequence(morse[string.char(ch)]) end end M.set_dit = function(duration) init(duration) end init(50000) return M
import java.util.*; public class MorseCode { final static String[][] code = { {"A", ".- "}, {"B", "-... "}, {"C", "-.-. "}, {"D", "-.. "}, {"E", ". "}, {"F", "..-. "}, {"G", "--. "}, {"H", ".... "}, {"I", ".. "}, {"J", ".--- "}, {"K", "-.- "}, {"L", ".-.. "}, {"M", "-- "}, {"N", "-. "}, {"O", "--- "}, {"P", ".--. "}, {"Q", "--.- "}, {"R", ".-. "}, {"S", "... "}, {"T", "- "}, {"U", "..- "}, {"V", "...- "}, {"W", ".- - "}, {"X", "-..- "}, {"Y", "-.-- "}, {"Z", "--.. "}, {"0", "----- "}, {"1", ".---- "}, {"2", "..--- "}, {"3", "...-- "}, {"4", "....- "}, {"5", "..... "}, {"6", "-.... "}, {"7", "--... "}, {"8", "---.. "}, {"9", "----. "}, {"'", ".----. "}, {":", "---... "}, {",", "--..-- "}, {"-", "-....- "}, {"(", "-.--.- "}, {".", ".-.-.- "}, {"?", "..--.. "}, {";", "-.-.-. "}, {"/", "-..-. "}, {"-", "..--.- "}, {")", "---.. "}, {"=", "-...- "}, {"@", ".--.-. "}, {"\"", ".-..-."}, {"+", ".-.-. "}, {" ", "/"}}; final static Map<Character, String> map = new HashMap<>(); static { for (String[] pair : code) map.put(pair[0].charAt(0), pair[1].trim()); } public static void main(String[] args) { printMorse("sos"); printMorse(" Hello World!"); printMorse("Rosetta Code"); } static void printMorse(String input) { System.out.printf("%s %n", input); input = input.trim().replaceAll("[ ]+", " ").toUpperCase(); for (char c : input.toCharArray()) { String s = map.get(c); if (s != null) System.out.printf("%s ", s); } System.out.println("\n"); } }
Convert the following code from Lua to Python, ensuring the logic remains intact.
local M = {} local BUZZER = pio.PB_10 local dit_length, dah_length, word_length local buzz, dah, dit, init, inter_element_gap, medium_gap, pause, sequence, short_gap buzz = function(duration) pio.pin.output(BUZZER) pio.pin.setlow(BUZZER) tmr.delay(tmr.SYS_TIMER, duration) pio.pin.sethigh(BUZZER) pio.pin.input(BUZZER) end dah = function() buzz(dah_length) end dit = function() buzz(dit_length) end init = function(baseline) dit_length = baseline dah_length = 2 * baseline word_length = 4 * baseline end inter_element_gap = function() pause(dit_length) end medium_gap = function() pause(word_length) end pause = function(duration) tmr.delay(tmr.SYS_TIMER, duration) end sequence = function(codes) if codes then for _,f in ipairs(codes) do f() inter_element_gap() end short_gap() end end short_gap = function() pause(dah_length) end local morse = { a = { dit, dah }, b = { dah, dit, dit, dit }, c = { dah, dit, dah, dit }, d = { dah, dit, dit }, e = { dit }, f = { dit, dit, dah, dit }, g = { dah, dah, dit }, h = { dit, dit, dit ,dit }, i = { dit, dit }, j = { dit, dah, dah, dah }, k = { dah, dit, dah }, l = { dit, dah, dit, dit }, m = { dah, dah }, n = { dah, dit }, o = { dah, dah, dah }, p = { dit, dah, dah, dit }, q = { dah, dah, dit, dah }, r = { dit, dah, dit }, s = { dit, dit, dit }, t = { dah }, u = { dit, dit, dah }, v = { dit, dit, dit, dah }, w = { dit, dah, dah }, x = { dah, dit, dit, dah }, y = { dah, dit, dah, dah }, z = { dah, dah, dit, dit }, ["0"] = { dah, dah, dah, dah, dah }, ["1"] = { dit, dah, dah, dah, dah }, ["2"] = { dit, dit, dah, dah, dah }, ["3"] = { dit, dit, dit, dah, dah }, ["4"] = { dit, dit, dit, dit, dah }, ["5"] = { dit, dit, dit, dit, dit }, ["6"] = { dah, dit, dit, dit, dit }, ["7"] = { dah, dah, dit, dit, dit }, ["8"] = { dah, dah, dah, dit, dit }, ["9"] = { dah, dah, dah, dah, dit }, [" "] = { medium_gap } } M.beep = function(message) message = message:lower() for _,ch in ipairs { message:byte(1, #message) } do sequence(morse[string.char(ch)]) end end M.set_dit = function(duration) init(duration) end init(50000) return M
import time, winsound char2morse = { "!": "---.", "\"": ".-..-.", "$": "...-..-", "'": ".----.", "(": "-.--.", ")": "-.--.-", "+": ".-.-.", ",": "--..--", "-": "-....-", ".": ".-.-.-", "/": "-..-.", "0": "-----", "1": ".----", "2": "..---", "3": "...--", "4": "....-", "5": ".....", "6": "-....", "7": "--...", "8": "---..", "9": "----.", ":": "---...", ";": "-.-.-.", "=": "-...-", "?": "..--..", "@": ".--.-.", "A": ".-", "B": "-...", "C": "-.-.", "D": "-..", "E": ".", "F": "..-.", "G": "--.", "H": "....", "I": "..", "J": ".---", "K": "-.-", "L": ".-..", "M": "--", "N": "-.", "O": "---", "P": ".--.", "Q": "--.-", "R": ".-.", "S": "...", "T": "-", "U": "..-", "V": "...-", "W": ".--", "X": "-..-", "Y": "-.--", "Z": "--..", "[": "-.--.", "]": "-.--.-", "_": "..--.-", } e = 50 f = 1280 chargap = 1 wordgap = 7 def gap(n=1): time.sleep(n * e / 1000) off = gap def on(n=1): winsound.Beep(f, n * e) def dit(): on(); off() def dah(): on(3); off() def bloop(n=3): winsound.Beep(f//2, n * e) def windowsmorse(text): for word in text.strip().upper().split(): for char in word: for element in char2morse.get(char, '?'): if element == '-': dah() elif element == '.': dit() else: bloop() gap(chargap) gap(wordgap) while True: windowsmorse(input('A string to change into morse: '))
Change the programming language of this snippet from Lua to VB without modifying what it does.
local M = {} local BUZZER = pio.PB_10 local dit_length, dah_length, word_length local buzz, dah, dit, init, inter_element_gap, medium_gap, pause, sequence, short_gap buzz = function(duration) pio.pin.output(BUZZER) pio.pin.setlow(BUZZER) tmr.delay(tmr.SYS_TIMER, duration) pio.pin.sethigh(BUZZER) pio.pin.input(BUZZER) end dah = function() buzz(dah_length) end dit = function() buzz(dit_length) end init = function(baseline) dit_length = baseline dah_length = 2 * baseline word_length = 4 * baseline end inter_element_gap = function() pause(dit_length) end medium_gap = function() pause(word_length) end pause = function(duration) tmr.delay(tmr.SYS_TIMER, duration) end sequence = function(codes) if codes then for _,f in ipairs(codes) do f() inter_element_gap() end short_gap() end end short_gap = function() pause(dah_length) end local morse = { a = { dit, dah }, b = { dah, dit, dit, dit }, c = { dah, dit, dah, dit }, d = { dah, dit, dit }, e = { dit }, f = { dit, dit, dah, dit }, g = { dah, dah, dit }, h = { dit, dit, dit ,dit }, i = { dit, dit }, j = { dit, dah, dah, dah }, k = { dah, dit, dah }, l = { dit, dah, dit, dit }, m = { dah, dah }, n = { dah, dit }, o = { dah, dah, dah }, p = { dit, dah, dah, dit }, q = { dah, dah, dit, dah }, r = { dit, dah, dit }, s = { dit, dit, dit }, t = { dah }, u = { dit, dit, dah }, v = { dit, dit, dit, dah }, w = { dit, dah, dah }, x = { dah, dit, dit, dah }, y = { dah, dit, dah, dah }, z = { dah, dah, dit, dit }, ["0"] = { dah, dah, dah, dah, dah }, ["1"] = { dit, dah, dah, dah, dah }, ["2"] = { dit, dit, dah, dah, dah }, ["3"] = { dit, dit, dit, dah, dah }, ["4"] = { dit, dit, dit, dit, dah }, ["5"] = { dit, dit, dit, dit, dit }, ["6"] = { dah, dit, dit, dit, dit }, ["7"] = { dah, dah, dit, dit, dit }, ["8"] = { dah, dah, dah, dit, dit }, ["9"] = { dah, dah, dah, dah, dit }, [" "] = { medium_gap } } M.beep = function(message) message = message:lower() for _,ch in ipairs { message:byte(1, #message) } do sequence(morse[string.char(ch)]) end end M.set_dit = function(duration) init(duration) end init(50000) return M
Option Explicit Private Declare Function Beep Lib "kernel32" (ByVal dwFreq As Long, ByVal dwDuration As Long) As Long Private Declare Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As Long) Private Const MORSE_ALPHA As String = ".-,-...,-.-.,-..,.,..-.,--.,....,..,.---,-.-,.-..,--,-.,---,.--.,--.-,.-.,...,-,..-,...-,.--,-..-,-.--,--.." Private Const MORSE_NUMERIC As String = "-----,.----,..---,...--,....-,.....,-....,--...,---..,----." Private Const ONE_UNIT As Integer = 100 Private Const BEEP_DOT As Integer = ONE_UNIT Private Const BEEP_DASH As Integer = 3 * ONE_UNIT Private Const BEEP_OTHER As Integer = 7 * ONE_UNIT Private Const DELAY As Integer = ONE_UNIT Private Const LETTERS_DELAY As Integer = 3 * ONE_UNIT Private Const SPACE_DELAY As Integer = 7 * ONE_UNIT Private Const FREQUENCY_CHARS As Integer = 1200 Private Const FREQUENCY_OTHERCHARS As Integer = 400 Sub Main() Dim p$, temp$ p = ToMorse("Hel/lo 123 world") temp = Replace(p, "+", "") Debug.Print Replace(temp, "_", "") PlayMorse p End Sub Private Function ToMorse(s As String) As String Dim i&, t$, j& s = UCase(s) For i = 1 To Len(s) j = Asc(Mid(s, i, 1)) Select Case j Case 65 To 90 t = t & Split(MORSE_ALPHA, ",")(j - 65) & "+" Case 48 To 57 t = t & Split(MORSE_NUMERIC, ",")(j - 48) & "+" Case 32 t = t & " " & "+" Case Else t = t & "_" & "+" End Select Next i ToMorse = t End Function Private Sub PlayMorse(s As String) Dim i& For i = 1 To Len(s) Select Case Mid(s, i, 1) Case ".": Beep FREQUENCY_CHARS, BEEP_DOT Case "-": Beep FREQUENCY_CHARS, BEEP_DASH Case "_": Beep FREQUENCY_OTHERCHARS, BEEP_OTHER Case "+": Sleep LETTERS_DELAY Case " ": Sleep SPACE_DELAY End Select Sleep DELAY Next i End Sub
Generate a Go translation of this Lua snippet without changing its computational steps.
local M = {} local BUZZER = pio.PB_10 local dit_length, dah_length, word_length local buzz, dah, dit, init, inter_element_gap, medium_gap, pause, sequence, short_gap buzz = function(duration) pio.pin.output(BUZZER) pio.pin.setlow(BUZZER) tmr.delay(tmr.SYS_TIMER, duration) pio.pin.sethigh(BUZZER) pio.pin.input(BUZZER) end dah = function() buzz(dah_length) end dit = function() buzz(dit_length) end init = function(baseline) dit_length = baseline dah_length = 2 * baseline word_length = 4 * baseline end inter_element_gap = function() pause(dit_length) end medium_gap = function() pause(word_length) end pause = function(duration) tmr.delay(tmr.SYS_TIMER, duration) end sequence = function(codes) if codes then for _,f in ipairs(codes) do f() inter_element_gap() end short_gap() end end short_gap = function() pause(dah_length) end local morse = { a = { dit, dah }, b = { dah, dit, dit, dit }, c = { dah, dit, dah, dit }, d = { dah, dit, dit }, e = { dit }, f = { dit, dit, dah, dit }, g = { dah, dah, dit }, h = { dit, dit, dit ,dit }, i = { dit, dit }, j = { dit, dah, dah, dah }, k = { dah, dit, dah }, l = { dit, dah, dit, dit }, m = { dah, dah }, n = { dah, dit }, o = { dah, dah, dah }, p = { dit, dah, dah, dit }, q = { dah, dah, dit, dah }, r = { dit, dah, dit }, s = { dit, dit, dit }, t = { dah }, u = { dit, dit, dah }, v = { dit, dit, dit, dah }, w = { dit, dah, dah }, x = { dah, dit, dit, dah }, y = { dah, dit, dah, dah }, z = { dah, dah, dit, dit }, ["0"] = { dah, dah, dah, dah, dah }, ["1"] = { dit, dah, dah, dah, dah }, ["2"] = { dit, dit, dah, dah, dah }, ["3"] = { dit, dit, dit, dah, dah }, ["4"] = { dit, dit, dit, dit, dah }, ["5"] = { dit, dit, dit, dit, dit }, ["6"] = { dah, dit, dit, dit, dit }, ["7"] = { dah, dah, dit, dit, dit }, ["8"] = { dah, dah, dah, dit, dit }, ["9"] = { dah, dah, dah, dah, dit }, [" "] = { medium_gap } } M.beep = function(message) message = message:lower() for _,ch in ipairs { message:byte(1, #message) } do sequence(morse[string.char(ch)]) end end M.set_dit = function(duration) init(duration) end init(50000) return M
package main import ( "flag" "fmt" "log" "regexp" "strings" "syscall" "time" "unicode" ) type key struct { duration int on bool sym string } var ( runeToKeys = map[rune][]key{} interCharGap = []key{{1, false, ""}} punctGap = []key{{7, false, " / "}} charGap = []key{{3, false, " "}} wordGap = []key{{7, false, " / "}} ) const rawMorse = ` A:.- J:.--- S:... 1:.---- .:.-.-.-  ::---... B:-... K:-.- T:- 2:..--- ,:--..--  ;:-.-.-. C:-.-. L:.-.. U:..- 3:...--  ?:..--.. =:-...- D:-.. M:-- V:...- 4:....- ':.----. +:.-.-. E:. N:-. W:.-- 5:.....  !:-.-.-- -:-....- F:..-. O:--- X:-..- 6:-.... /:-..-. _:..--.- G:--. P:.--. Y:-.-- 7:--... (:-.--. ":.-..-. H:.... Q:--.- Z:--.. 8:---.. ):-.--.- $:...-..- I:.. R:.-. 0:----- 9:----. &:.-... @:.--.-. ` func init() { r := regexp.MustCompile("([^ ]):([.-]+)") for _, m := range r.FindAllStringSubmatch(rawMorse, -1) { c := m[1][0] keys := []key{} for i, dd := range m[2] { if i > 0 { keys = append(keys, interCharGap...) } if dd == '.' { keys = append(keys, key{1, true, "."}) } else if dd == '-' { keys = append(keys, key{3, true, "-"}) } else { log.Fatalf("found %c in morse for %c", dd, c) } runeToKeys[rune(c)] = keys runeToKeys[unicode.ToLower(rune(c))] = keys } } } func MorseKeys(in string) ([]key, error) { afterWord := false afterChar := false result := []key{} for _, c := range in { if unicode.IsSpace(c) { afterWord = true continue } morse, ok := runeToKeys[c] if !ok { return nil, fmt.Errorf("can't translate %c to morse", c) } if unicode.IsPunct(c) && afterChar { result = append(result, punctGap...) } else if afterWord { result = append(result, wordGap...) } else if afterChar { result = append(result, charGap...) } result = append(result, morse...) afterChar = true afterWord = false } return result, nil } func main() { var ditDuration time.Duration flag.DurationVar(&ditDuration, "d", 40*time.Millisecond, "length of dit") flag.Parse() in := "hello world." if len(flag.Args()) > 1 { in = strings.Join(flag.Args(), " ") } keys, err := MorseKeys(in) if err != nil { log.Fatalf("failed to translate: %s", err) } for _, k := range keys { if k.on { if err := note(true); err != nil { log.Fatalf("failed to play note: %s", err) } } fmt.Print(k.sym) time.Sleep(ditDuration * time.Duration(k.duration)) if k.on { if err := note(false); err != nil { log.Fatalf("failed to stop note: %s", err) } } } fmt.Println() } var consoleFD uintptr func init() { fd, err := syscall.Open("/dev/console", syscall.O_WRONLY, 0) if err != nil { log.Fatalf("failed to get console device: %s", err) } consoleFD = uintptr(fd) } const KIOCSOUND = 0x4B2F const clockTickRate = 1193180 const freqHz = 600 func note(on bool) error { arg := uintptr(0) if on { arg = clockTickRate / freqHz } _, _, errno := syscall.Syscall(syscall.SYS_IOCTL, consoleFD, KIOCSOUND, arg) if errno != 0 { return errno } return nil }
Translate this program into C but keep the logic exactly as in Mathematica.
Dictionary = Join[CharacterRange["a", "z"], CharacterRange["0", "9"]]; mark = 0.1; gap = 0.125; shortgap = 3*gap; medgap = 7*gap; longmark = 3*mark; MorseDictionary = { ".-", "-...", "-.-.", "-..", ".", "..-.", "--.", "....", "..", ".---", "-.-", ".-..", "--", "-.", "---", ".--.", "--.-", ".-.", "...", "-", "..-", "...-", ".--", "-..-", "-.--", "--..", "-----", ".----", "..---", "...--", "....-", ".....", "-....", "--...", "---..", "----." }; MorseDictionary = # <> " " & /@ MorseDictionary; Tones = { SoundNote[None, medgap], SoundNote[None, shortgap], {SoundNote["C", mark, "Clarinet"], SoundNote[None, gap]}, {SoundNote["C", longmark, "Clarinet"], SoundNote[None, gap]}, {SoundNote["F#", mark, "Clarinet"], SoundNote[None, gap]} }; codeRules = MapThread[Rule, {Dictionary, MorseDictionary}]; decodeRules = MapThread[Rule, {MorseDictionary, Dictionary}]; soundRules = MapThread[Rule, {{" ", " ", ".", "-", "?"}, Tones}]; morseCode[s_String] := StringReplace[ToLowerCase@s, codeRules~Join~{x_ /; FreeQ[Flatten@{Dictionary, " "}, x] -> "? "}] morseDecode[s_String] := StringReplace[s, decodeRules] sonicMorse[s_String] := EmitSound@Sound@Flatten[Characters@morseCode@s /. soundRules]
#include <ctype.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #define BIND(A,L,H) ((L)<(A)?(A)<(H)?(A):(H):(L)) char dih[50],dah[50],medium[30],word[30], *dd[2] = {dih,dah}; const char *ascii = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789.,?'!/()&:;=+-_\"$@", *itu[] = { "13","3111","3131","311","1","1131","331","1111","11","1333","313","1311","33","31","333","1331","3313","131","111","3","113","1113","133","3113","3133","3311","33333","13333","11333","11133","11113","11111","31111","33111","33311","33331","131313","331133","113311","133331","313133","31131","31331","313313","13111","333111","313131","31113","13131","311113","113313","131131","1113113","133131" }; void append(char*s,const char*morse) { for (; *morse; ++morse) strcat(s,dd['3'==*morse]); strcat(s,medium); } char*translate(const char*i,char*o) { const char*pc; sprintf(o,"beep"); for (; *i; ++i) if (NULL == (pc = strchr(ascii,toupper(*i)))) strcat(o,word); else append(o,itu[pc-ascii]); strcat(o,word); return o; } int main(int ac,char*av[]) { char sin[73],sout[100000]; int dit = 100; if (1 < ac) { if (strlen(av[1]) != strspn(av[1],"0123456789")) return 0*fprintf(stderr,"use: %s [duration] dit in ms, default %d\n",*av,dit); dit = BIND(atoi(av[1]),1,1000); } sprintf(dah," -n -f 440 -l %d -D %d",3*dit,dit); sprintf(dih," -n -f 440 -l %d -D %d",dit,dit); sprintf(medium," -n -D %d",(3-1)*dit); sprintf(word," -n -D %d",(7-(3-1)-1)*dit); while (NULL != fgets(sin,72,stdin)) puts(translate(sin,sout)); return 0; }
Write the same code in C# as shown below in Mathematica.
Dictionary = Join[CharacterRange["a", "z"], CharacterRange["0", "9"]]; mark = 0.1; gap = 0.125; shortgap = 3*gap; medgap = 7*gap; longmark = 3*mark; MorseDictionary = { ".-", "-...", "-.-.", "-..", ".", "..-.", "--.", "....", "..", ".---", "-.-", ".-..", "--", "-.", "---", ".--.", "--.-", ".-.", "...", "-", "..-", "...-", ".--", "-..-", "-.--", "--..", "-----", ".----", "..---", "...--", "....-", ".....", "-....", "--...", "---..", "----." }; MorseDictionary = # <> " " & /@ MorseDictionary; Tones = { SoundNote[None, medgap], SoundNote[None, shortgap], {SoundNote["C", mark, "Clarinet"], SoundNote[None, gap]}, {SoundNote["C", longmark, "Clarinet"], SoundNote[None, gap]}, {SoundNote["F#", mark, "Clarinet"], SoundNote[None, gap]} }; codeRules = MapThread[Rule, {Dictionary, MorseDictionary}]; decodeRules = MapThread[Rule, {MorseDictionary, Dictionary}]; soundRules = MapThread[Rule, {{" ", " ", ".", "-", "?"}, Tones}]; morseCode[s_String] := StringReplace[ToLowerCase@s, codeRules~Join~{x_ /; FreeQ[Flatten@{Dictionary, " "}, x] -> "? "}] morseDecode[s_String] := StringReplace[s, decodeRules] sonicMorse[s_String] := EmitSound@Sound@Flatten[Characters@morseCode@s /. soundRules]
using System; using System.Collections.Generic; namespace Morse { class Morse { static void Main(string[] args) { string word = "sos"; Dictionary<string, string> Codes = new Dictionary<string, string> { {"a", ".- "}, {"b", "-... "}, {"c", "-.-. "}, {"d", "-.. "}, {"e", ". "}, {"f", "..-. "}, {"g", "--. "}, {"h", ".... "}, {"i", ".. "}, {"j", ".--- "}, {"k", "-.- "}, {"l", ".-.. "}, {"m", "-- "}, {"n", "-. "}, {"o", "--- "}, {"p", ".--. "}, {"q", "--.- "}, {"r", ".-. "}, {"s", "... "}, {"t", "- "}, {"u", "..- "}, {"v", "...- "}, {"w", ".-- "}, {"x", "-..- "}, {"y", "-.-- "}, {"z", "--.. "}, {"0", "-----"}, {"1", ".----"}, {"2", "..---"}, {"3", "...--"}, {"4", "....-"}, {"5", "....."}, {"6", "-...."}, {"7", "--..."}, {"8", "---.."}, {"9", "----."} }; foreach (char c in word.ToCharArray()) { string rslt = Codes[c.ToString()].Trim(); foreach (char c2 in rslt.ToCharArray()) { if (c2 == '.') Console.Beep(1000, 250); else Console.Beep(1000, 750); } System.Threading.Thread.Sleep(50); } } } }
Please provide an equivalent version of this Mathematica code in Java.
Dictionary = Join[CharacterRange["a", "z"], CharacterRange["0", "9"]]; mark = 0.1; gap = 0.125; shortgap = 3*gap; medgap = 7*gap; longmark = 3*mark; MorseDictionary = { ".-", "-...", "-.-.", "-..", ".", "..-.", "--.", "....", "..", ".---", "-.-", ".-..", "--", "-.", "---", ".--.", "--.-", ".-.", "...", "-", "..-", "...-", ".--", "-..-", "-.--", "--..", "-----", ".----", "..---", "...--", "....-", ".....", "-....", "--...", "---..", "----." }; MorseDictionary = # <> " " & /@ MorseDictionary; Tones = { SoundNote[None, medgap], SoundNote[None, shortgap], {SoundNote["C", mark, "Clarinet"], SoundNote[None, gap]}, {SoundNote["C", longmark, "Clarinet"], SoundNote[None, gap]}, {SoundNote["F#", mark, "Clarinet"], SoundNote[None, gap]} }; codeRules = MapThread[Rule, {Dictionary, MorseDictionary}]; decodeRules = MapThread[Rule, {MorseDictionary, Dictionary}]; soundRules = MapThread[Rule, {{" ", " ", ".", "-", "?"}, Tones}]; morseCode[s_String] := StringReplace[ToLowerCase@s, codeRules~Join~{x_ /; FreeQ[Flatten@{Dictionary, " "}, x] -> "? "}] morseDecode[s_String] := StringReplace[s, decodeRules] sonicMorse[s_String] := EmitSound@Sound@Flatten[Characters@morseCode@s /. soundRules]
import java.util.*; public class MorseCode { final static String[][] code = { {"A", ".- "}, {"B", "-... "}, {"C", "-.-. "}, {"D", "-.. "}, {"E", ". "}, {"F", "..-. "}, {"G", "--. "}, {"H", ".... "}, {"I", ".. "}, {"J", ".--- "}, {"K", "-.- "}, {"L", ".-.. "}, {"M", "-- "}, {"N", "-. "}, {"O", "--- "}, {"P", ".--. "}, {"Q", "--.- "}, {"R", ".-. "}, {"S", "... "}, {"T", "- "}, {"U", "..- "}, {"V", "...- "}, {"W", ".- - "}, {"X", "-..- "}, {"Y", "-.-- "}, {"Z", "--.. "}, {"0", "----- "}, {"1", ".---- "}, {"2", "..--- "}, {"3", "...-- "}, {"4", "....- "}, {"5", "..... "}, {"6", "-.... "}, {"7", "--... "}, {"8", "---.. "}, {"9", "----. "}, {"'", ".----. "}, {":", "---... "}, {",", "--..-- "}, {"-", "-....- "}, {"(", "-.--.- "}, {".", ".-.-.- "}, {"?", "..--.. "}, {";", "-.-.-. "}, {"/", "-..-. "}, {"-", "..--.- "}, {")", "---.. "}, {"=", "-...- "}, {"@", ".--.-. "}, {"\"", ".-..-."}, {"+", ".-.-. "}, {" ", "/"}}; final static Map<Character, String> map = new HashMap<>(); static { for (String[] pair : code) map.put(pair[0].charAt(0), pair[1].trim()); } public static void main(String[] args) { printMorse("sos"); printMorse(" Hello World!"); printMorse("Rosetta Code"); } static void printMorse(String input) { System.out.printf("%s %n", input); input = input.trim().replaceAll("[ ]+", " ").toUpperCase(); for (char c : input.toCharArray()) { String s = map.get(c); if (s != null) System.out.printf("%s ", s); } System.out.println("\n"); } }
Convert the following code from Mathematica to Python, ensuring the logic remains intact.
Dictionary = Join[CharacterRange["a", "z"], CharacterRange["0", "9"]]; mark = 0.1; gap = 0.125; shortgap = 3*gap; medgap = 7*gap; longmark = 3*mark; MorseDictionary = { ".-", "-...", "-.-.", "-..", ".", "..-.", "--.", "....", "..", ".---", "-.-", ".-..", "--", "-.", "---", ".--.", "--.-", ".-.", "...", "-", "..-", "...-", ".--", "-..-", "-.--", "--..", "-----", ".----", "..---", "...--", "....-", ".....", "-....", "--...", "---..", "----." }; MorseDictionary = # <> " " & /@ MorseDictionary; Tones = { SoundNote[None, medgap], SoundNote[None, shortgap], {SoundNote["C", mark, "Clarinet"], SoundNote[None, gap]}, {SoundNote["C", longmark, "Clarinet"], SoundNote[None, gap]}, {SoundNote["F#", mark, "Clarinet"], SoundNote[None, gap]} }; codeRules = MapThread[Rule, {Dictionary, MorseDictionary}]; decodeRules = MapThread[Rule, {MorseDictionary, Dictionary}]; soundRules = MapThread[Rule, {{" ", " ", ".", "-", "?"}, Tones}]; morseCode[s_String] := StringReplace[ToLowerCase@s, codeRules~Join~{x_ /; FreeQ[Flatten@{Dictionary, " "}, x] -> "? "}] morseDecode[s_String] := StringReplace[s, decodeRules] sonicMorse[s_String] := EmitSound@Sound@Flatten[Characters@morseCode@s /. soundRules]
import time, winsound char2morse = { "!": "---.", "\"": ".-..-.", "$": "...-..-", "'": ".----.", "(": "-.--.", ")": "-.--.-", "+": ".-.-.", ",": "--..--", "-": "-....-", ".": ".-.-.-", "/": "-..-.", "0": "-----", "1": ".----", "2": "..---", "3": "...--", "4": "....-", "5": ".....", "6": "-....", "7": "--...", "8": "---..", "9": "----.", ":": "---...", ";": "-.-.-.", "=": "-...-", "?": "..--..", "@": ".--.-.", "A": ".-", "B": "-...", "C": "-.-.", "D": "-..", "E": ".", "F": "..-.", "G": "--.", "H": "....", "I": "..", "J": ".---", "K": "-.-", "L": ".-..", "M": "--", "N": "-.", "O": "---", "P": ".--.", "Q": "--.-", "R": ".-.", "S": "...", "T": "-", "U": "..-", "V": "...-", "W": ".--", "X": "-..-", "Y": "-.--", "Z": "--..", "[": "-.--.", "]": "-.--.-", "_": "..--.-", } e = 50 f = 1280 chargap = 1 wordgap = 7 def gap(n=1): time.sleep(n * e / 1000) off = gap def on(n=1): winsound.Beep(f, n * e) def dit(): on(); off() def dah(): on(3); off() def bloop(n=3): winsound.Beep(f//2, n * e) def windowsmorse(text): for word in text.strip().upper().split(): for char in word: for element in char2morse.get(char, '?'): if element == '-': dah() elif element == '.': dit() else: bloop() gap(chargap) gap(wordgap) while True: windowsmorse(input('A string to change into morse: '))
Write a version of this Mathematica function in VB with identical behavior.
Dictionary = Join[CharacterRange["a", "z"], CharacterRange["0", "9"]]; mark = 0.1; gap = 0.125; shortgap = 3*gap; medgap = 7*gap; longmark = 3*mark; MorseDictionary = { ".-", "-...", "-.-.", "-..", ".", "..-.", "--.", "....", "..", ".---", "-.-", ".-..", "--", "-.", "---", ".--.", "--.-", ".-.", "...", "-", "..-", "...-", ".--", "-..-", "-.--", "--..", "-----", ".----", "..---", "...--", "....-", ".....", "-....", "--...", "---..", "----." }; MorseDictionary = # <> " " & /@ MorseDictionary; Tones = { SoundNote[None, medgap], SoundNote[None, shortgap], {SoundNote["C", mark, "Clarinet"], SoundNote[None, gap]}, {SoundNote["C", longmark, "Clarinet"], SoundNote[None, gap]}, {SoundNote["F#", mark, "Clarinet"], SoundNote[None, gap]} }; codeRules = MapThread[Rule, {Dictionary, MorseDictionary}]; decodeRules = MapThread[Rule, {MorseDictionary, Dictionary}]; soundRules = MapThread[Rule, {{" ", " ", ".", "-", "?"}, Tones}]; morseCode[s_String] := StringReplace[ToLowerCase@s, codeRules~Join~{x_ /; FreeQ[Flatten@{Dictionary, " "}, x] -> "? "}] morseDecode[s_String] := StringReplace[s, decodeRules] sonicMorse[s_String] := EmitSound@Sound@Flatten[Characters@morseCode@s /. soundRules]
Option Explicit Private Declare Function Beep Lib "kernel32" (ByVal dwFreq As Long, ByVal dwDuration As Long) As Long Private Declare Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As Long) Private Const MORSE_ALPHA As String = ".-,-...,-.-.,-..,.,..-.,--.,....,..,.---,-.-,.-..,--,-.,---,.--.,--.-,.-.,...,-,..-,...-,.--,-..-,-.--,--.." Private Const MORSE_NUMERIC As String = "-----,.----,..---,...--,....-,.....,-....,--...,---..,----." Private Const ONE_UNIT As Integer = 100 Private Const BEEP_DOT As Integer = ONE_UNIT Private Const BEEP_DASH As Integer = 3 * ONE_UNIT Private Const BEEP_OTHER As Integer = 7 * ONE_UNIT Private Const DELAY As Integer = ONE_UNIT Private Const LETTERS_DELAY As Integer = 3 * ONE_UNIT Private Const SPACE_DELAY As Integer = 7 * ONE_UNIT Private Const FREQUENCY_CHARS As Integer = 1200 Private Const FREQUENCY_OTHERCHARS As Integer = 400 Sub Main() Dim p$, temp$ p = ToMorse("Hel/lo 123 world") temp = Replace(p, "+", "") Debug.Print Replace(temp, "_", "") PlayMorse p End Sub Private Function ToMorse(s As String) As String Dim i&, t$, j& s = UCase(s) For i = 1 To Len(s) j = Asc(Mid(s, i, 1)) Select Case j Case 65 To 90 t = t & Split(MORSE_ALPHA, ",")(j - 65) & "+" Case 48 To 57 t = t & Split(MORSE_NUMERIC, ",")(j - 48) & "+" Case 32 t = t & " " & "+" Case Else t = t & "_" & "+" End Select Next i ToMorse = t End Function Private Sub PlayMorse(s As String) Dim i& For i = 1 To Len(s) Select Case Mid(s, i, 1) Case ".": Beep FREQUENCY_CHARS, BEEP_DOT Case "-": Beep FREQUENCY_CHARS, BEEP_DASH Case "_": Beep FREQUENCY_OTHERCHARS, BEEP_OTHER Case "+": Sleep LETTERS_DELAY Case " ": Sleep SPACE_DELAY End Select Sleep DELAY Next i End Sub
Translate the given Mathematica code snippet into Go without altering its behavior.
Dictionary = Join[CharacterRange["a", "z"], CharacterRange["0", "9"]]; mark = 0.1; gap = 0.125; shortgap = 3*gap; medgap = 7*gap; longmark = 3*mark; MorseDictionary = { ".-", "-...", "-.-.", "-..", ".", "..-.", "--.", "....", "..", ".---", "-.-", ".-..", "--", "-.", "---", ".--.", "--.-", ".-.", "...", "-", "..-", "...-", ".--", "-..-", "-.--", "--..", "-----", ".----", "..---", "...--", "....-", ".....", "-....", "--...", "---..", "----." }; MorseDictionary = # <> " " & /@ MorseDictionary; Tones = { SoundNote[None, medgap], SoundNote[None, shortgap], {SoundNote["C", mark, "Clarinet"], SoundNote[None, gap]}, {SoundNote["C", longmark, "Clarinet"], SoundNote[None, gap]}, {SoundNote["F#", mark, "Clarinet"], SoundNote[None, gap]} }; codeRules = MapThread[Rule, {Dictionary, MorseDictionary}]; decodeRules = MapThread[Rule, {MorseDictionary, Dictionary}]; soundRules = MapThread[Rule, {{" ", " ", ".", "-", "?"}, Tones}]; morseCode[s_String] := StringReplace[ToLowerCase@s, codeRules~Join~{x_ /; FreeQ[Flatten@{Dictionary, " "}, x] -> "? "}] morseDecode[s_String] := StringReplace[s, decodeRules] sonicMorse[s_String] := EmitSound@Sound@Flatten[Characters@morseCode@s /. soundRules]
package main import ( "flag" "fmt" "log" "regexp" "strings" "syscall" "time" "unicode" ) type key struct { duration int on bool sym string } var ( runeToKeys = map[rune][]key{} interCharGap = []key{{1, false, ""}} punctGap = []key{{7, false, " / "}} charGap = []key{{3, false, " "}} wordGap = []key{{7, false, " / "}} ) const rawMorse = ` A:.- J:.--- S:... 1:.---- .:.-.-.-  ::---... B:-... K:-.- T:- 2:..--- ,:--..--  ;:-.-.-. C:-.-. L:.-.. U:..- 3:...--  ?:..--.. =:-...- D:-.. M:-- V:...- 4:....- ':.----. +:.-.-. E:. N:-. W:.-- 5:.....  !:-.-.-- -:-....- F:..-. O:--- X:-..- 6:-.... /:-..-. _:..--.- G:--. P:.--. Y:-.-- 7:--... (:-.--. ":.-..-. H:.... Q:--.- Z:--.. 8:---.. ):-.--.- $:...-..- I:.. R:.-. 0:----- 9:----. &:.-... @:.--.-. ` func init() { r := regexp.MustCompile("([^ ]):([.-]+)") for _, m := range r.FindAllStringSubmatch(rawMorse, -1) { c := m[1][0] keys := []key{} for i, dd := range m[2] { if i > 0 { keys = append(keys, interCharGap...) } if dd == '.' { keys = append(keys, key{1, true, "."}) } else if dd == '-' { keys = append(keys, key{3, true, "-"}) } else { log.Fatalf("found %c in morse for %c", dd, c) } runeToKeys[rune(c)] = keys runeToKeys[unicode.ToLower(rune(c))] = keys } } } func MorseKeys(in string) ([]key, error) { afterWord := false afterChar := false result := []key{} for _, c := range in { if unicode.IsSpace(c) { afterWord = true continue } morse, ok := runeToKeys[c] if !ok { return nil, fmt.Errorf("can't translate %c to morse", c) } if unicode.IsPunct(c) && afterChar { result = append(result, punctGap...) } else if afterWord { result = append(result, wordGap...) } else if afterChar { result = append(result, charGap...) } result = append(result, morse...) afterChar = true afterWord = false } return result, nil } func main() { var ditDuration time.Duration flag.DurationVar(&ditDuration, "d", 40*time.Millisecond, "length of dit") flag.Parse() in := "hello world." if len(flag.Args()) > 1 { in = strings.Join(flag.Args(), " ") } keys, err := MorseKeys(in) if err != nil { log.Fatalf("failed to translate: %s", err) } for _, k := range keys { if k.on { if err := note(true); err != nil { log.Fatalf("failed to play note: %s", err) } } fmt.Print(k.sym) time.Sleep(ditDuration * time.Duration(k.duration)) if k.on { if err := note(false); err != nil { log.Fatalf("failed to stop note: %s", err) } } } fmt.Println() } var consoleFD uintptr func init() { fd, err := syscall.Open("/dev/console", syscall.O_WRONLY, 0) if err != nil { log.Fatalf("failed to get console device: %s", err) } consoleFD = uintptr(fd) } const KIOCSOUND = 0x4B2F const clockTickRate = 1193180 const freqHz = 600 func note(on bool) error { arg := uintptr(0) if on { arg = clockTickRate / freqHz } _, _, errno := syscall.Syscall(syscall.SYS_IOCTL, consoleFD, KIOCSOUND, arg) if errno != 0 { return errno } return nil }
Generate an equivalent C version of this MATLAB code.
function [morseText,morseSound] = text2morse(string,playSound) string = lower(string); morseDictionary = {{' ',' '},{'',''},{'',''},{'',''},... {'',''},{'',''},{'',''},{'',''},{'',''},{'',''},... {'',''},{'',''},{'',''},{'',''},{'',''},{'',''},... {'0','-----'},{'1','.----'},{'2','..---'},{'3','...--'},... {'4','....-'},{'5','.....'},{'6','-....'},{'7','--...'},... {'8','---..'},{'9','----.'},... {'',''},{'',''},{'',''},{'',''},{'',''},{'',''},... {'',''},{'',''},{'',''},{'',''},{'',''},{'',''},... {'',''},{'',''},{'',''},{'',''},{'',''},{'',''},... {'',''},{'',''},{'',''},{'',''},{'',''},{'',''},... {'',''},{'',''},{'',''},{'',''},{'',''},{'',''},... {'',''},{'',''},{'',''},{'',''},{'',''},{'',''},... {'',''},{'',''},{'',''},... {'a','.-'},{'b','-...'},{'c','-.-.'},{'d','-..'},... {'e','.'},{'f','..-.'},{'g','--.'},{'h','....'},... {'i','..'},{'j','.---'},{'k','-.-'},{'l','.-..'},... {'m','--'},{'n','-.'},{'o','---'},{'p','.--.'},... {'q','--.-'},{'r','.-.'},{'s','...'},{'t','-'},... {'u','..-'},{'v','...-'},{'w','.--'},{'x','-..-'},... {'y','-.--'},{'z','--..'}}; morseText = arrayfun(@(x)[morseDictionary{x}{2} '|'],(string - 31),'UniformOutput',false); morseText = cell2mat(morseText); morseText(end) = []; SamplingFrequency = 8192; ditLength = .1; dit = (0:1/SamplingFrequency:ditLength); dah = (0:1/SamplingFrequency:3*ditLength); dit = sin(3520*dit); dah = sin(3520*dah); silent = zeros(1,length(dit)); morseTiming = {{'.',[dit silent]},{'-',[dah silent]},{'|',[silent silent]},{' ',[silent silent]}}; morseSound = []; for i = (1:length(morseText)) cellNum = find(cellfun(@(x)(x{1}==morseText(i)),morseTiming)); morseSound = [morseSound morseTiming{cellNum}{2}]; end morseSound(end-length(silent):end) = []; if(playSound) sound(morseSound,SamplingFrequency); end end
#include <ctype.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #define BIND(A,L,H) ((L)<(A)?(A)<(H)?(A):(H):(L)) char dih[50],dah[50],medium[30],word[30], *dd[2] = {dih,dah}; const char *ascii = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789.,?'!/()&:;=+-_\"$@", *itu[] = { "13","3111","3131","311","1","1131","331","1111","11","1333","313","1311","33","31","333","1331","3313","131","111","3","113","1113","133","3113","3133","3311","33333","13333","11333","11133","11113","11111","31111","33111","33311","33331","131313","331133","113311","133331","313133","31131","31331","313313","13111","333111","313131","31113","13131","311113","113313","131131","1113113","133131" }; void append(char*s,const char*morse) { for (; *morse; ++morse) strcat(s,dd['3'==*morse]); strcat(s,medium); } char*translate(const char*i,char*o) { const char*pc; sprintf(o,"beep"); for (; *i; ++i) if (NULL == (pc = strchr(ascii,toupper(*i)))) strcat(o,word); else append(o,itu[pc-ascii]); strcat(o,word); return o; } int main(int ac,char*av[]) { char sin[73],sout[100000]; int dit = 100; if (1 < ac) { if (strlen(av[1]) != strspn(av[1],"0123456789")) return 0*fprintf(stderr,"use: %s [duration] dit in ms, default %d\n",*av,dit); dit = BIND(atoi(av[1]),1,1000); } sprintf(dah," -n -f 440 -l %d -D %d",3*dit,dit); sprintf(dih," -n -f 440 -l %d -D %d",dit,dit); sprintf(medium," -n -D %d",(3-1)*dit); sprintf(word," -n -D %d",(7-(3-1)-1)*dit); while (NULL != fgets(sin,72,stdin)) puts(translate(sin,sout)); return 0; }
Write the same algorithm in C# as shown in this MATLAB implementation.
function [morseText,morseSound] = text2morse(string,playSound) string = lower(string); morseDictionary = {{' ',' '},{'',''},{'',''},{'',''},... {'',''},{'',''},{'',''},{'',''},{'',''},{'',''},... {'',''},{'',''},{'',''},{'',''},{'',''},{'',''},... {'0','-----'},{'1','.----'},{'2','..---'},{'3','...--'},... {'4','....-'},{'5','.....'},{'6','-....'},{'7','--...'},... {'8','---..'},{'9','----.'},... {'',''},{'',''},{'',''},{'',''},{'',''},{'',''},... {'',''},{'',''},{'',''},{'',''},{'',''},{'',''},... {'',''},{'',''},{'',''},{'',''},{'',''},{'',''},... {'',''},{'',''},{'',''},{'',''},{'',''},{'',''},... {'',''},{'',''},{'',''},{'',''},{'',''},{'',''},... {'',''},{'',''},{'',''},{'',''},{'',''},{'',''},... {'',''},{'',''},{'',''},... {'a','.-'},{'b','-...'},{'c','-.-.'},{'d','-..'},... {'e','.'},{'f','..-.'},{'g','--.'},{'h','....'},... {'i','..'},{'j','.---'},{'k','-.-'},{'l','.-..'},... {'m','--'},{'n','-.'},{'o','---'},{'p','.--.'},... {'q','--.-'},{'r','.-.'},{'s','...'},{'t','-'},... {'u','..-'},{'v','...-'},{'w','.--'},{'x','-..-'},... {'y','-.--'},{'z','--..'}}; morseText = arrayfun(@(x)[morseDictionary{x}{2} '|'],(string - 31),'UniformOutput',false); morseText = cell2mat(morseText); morseText(end) = []; SamplingFrequency = 8192; ditLength = .1; dit = (0:1/SamplingFrequency:ditLength); dah = (0:1/SamplingFrequency:3*ditLength); dit = sin(3520*dit); dah = sin(3520*dah); silent = zeros(1,length(dit)); morseTiming = {{'.',[dit silent]},{'-',[dah silent]},{'|',[silent silent]},{' ',[silent silent]}}; morseSound = []; for i = (1:length(morseText)) cellNum = find(cellfun(@(x)(x{1}==morseText(i)),morseTiming)); morseSound = [morseSound morseTiming{cellNum}{2}]; end morseSound(end-length(silent):end) = []; if(playSound) sound(morseSound,SamplingFrequency); end end
using System; using System.Collections.Generic; namespace Morse { class Morse { static void Main(string[] args) { string word = "sos"; Dictionary<string, string> Codes = new Dictionary<string, string> { {"a", ".- "}, {"b", "-... "}, {"c", "-.-. "}, {"d", "-.. "}, {"e", ". "}, {"f", "..-. "}, {"g", "--. "}, {"h", ".... "}, {"i", ".. "}, {"j", ".--- "}, {"k", "-.- "}, {"l", ".-.. "}, {"m", "-- "}, {"n", "-. "}, {"o", "--- "}, {"p", ".--. "}, {"q", "--.- "}, {"r", ".-. "}, {"s", "... "}, {"t", "- "}, {"u", "..- "}, {"v", "...- "}, {"w", ".-- "}, {"x", "-..- "}, {"y", "-.-- "}, {"z", "--.. "}, {"0", "-----"}, {"1", ".----"}, {"2", "..---"}, {"3", "...--"}, {"4", "....-"}, {"5", "....."}, {"6", "-...."}, {"7", "--..."}, {"8", "---.."}, {"9", "----."} }; foreach (char c in word.ToCharArray()) { string rslt = Codes[c.ToString()].Trim(); foreach (char c2 in rslt.ToCharArray()) { if (c2 == '.') Console.Beep(1000, 250); else Console.Beep(1000, 750); } System.Threading.Thread.Sleep(50); } } } }
Produce a functionally identical Java code for the snippet given in MATLAB.
function [morseText,morseSound] = text2morse(string,playSound) string = lower(string); morseDictionary = {{' ',' '},{'',''},{'',''},{'',''},... {'',''},{'',''},{'',''},{'',''},{'',''},{'',''},... {'',''},{'',''},{'',''},{'',''},{'',''},{'',''},... {'0','-----'},{'1','.----'},{'2','..---'},{'3','...--'},... {'4','....-'},{'5','.....'},{'6','-....'},{'7','--...'},... {'8','---..'},{'9','----.'},... {'',''},{'',''},{'',''},{'',''},{'',''},{'',''},... {'',''},{'',''},{'',''},{'',''},{'',''},{'',''},... {'',''},{'',''},{'',''},{'',''},{'',''},{'',''},... {'',''},{'',''},{'',''},{'',''},{'',''},{'',''},... {'',''},{'',''},{'',''},{'',''},{'',''},{'',''},... {'',''},{'',''},{'',''},{'',''},{'',''},{'',''},... {'',''},{'',''},{'',''},... {'a','.-'},{'b','-...'},{'c','-.-.'},{'d','-..'},... {'e','.'},{'f','..-.'},{'g','--.'},{'h','....'},... {'i','..'},{'j','.---'},{'k','-.-'},{'l','.-..'},... {'m','--'},{'n','-.'},{'o','---'},{'p','.--.'},... {'q','--.-'},{'r','.-.'},{'s','...'},{'t','-'},... {'u','..-'},{'v','...-'},{'w','.--'},{'x','-..-'},... {'y','-.--'},{'z','--..'}}; morseText = arrayfun(@(x)[morseDictionary{x}{2} '|'],(string - 31),'UniformOutput',false); morseText = cell2mat(morseText); morseText(end) = []; SamplingFrequency = 8192; ditLength = .1; dit = (0:1/SamplingFrequency:ditLength); dah = (0:1/SamplingFrequency:3*ditLength); dit = sin(3520*dit); dah = sin(3520*dah); silent = zeros(1,length(dit)); morseTiming = {{'.',[dit silent]},{'-',[dah silent]},{'|',[silent silent]},{' ',[silent silent]}}; morseSound = []; for i = (1:length(morseText)) cellNum = find(cellfun(@(x)(x{1}==morseText(i)),morseTiming)); morseSound = [morseSound morseTiming{cellNum}{2}]; end morseSound(end-length(silent):end) = []; if(playSound) sound(morseSound,SamplingFrequency); end end
import java.util.*; public class MorseCode { final static String[][] code = { {"A", ".- "}, {"B", "-... "}, {"C", "-.-. "}, {"D", "-.. "}, {"E", ". "}, {"F", "..-. "}, {"G", "--. "}, {"H", ".... "}, {"I", ".. "}, {"J", ".--- "}, {"K", "-.- "}, {"L", ".-.. "}, {"M", "-- "}, {"N", "-. "}, {"O", "--- "}, {"P", ".--. "}, {"Q", "--.- "}, {"R", ".-. "}, {"S", "... "}, {"T", "- "}, {"U", "..- "}, {"V", "...- "}, {"W", ".- - "}, {"X", "-..- "}, {"Y", "-.-- "}, {"Z", "--.. "}, {"0", "----- "}, {"1", ".---- "}, {"2", "..--- "}, {"3", "...-- "}, {"4", "....- "}, {"5", "..... "}, {"6", "-.... "}, {"7", "--... "}, {"8", "---.. "}, {"9", "----. "}, {"'", ".----. "}, {":", "---... "}, {",", "--..-- "}, {"-", "-....- "}, {"(", "-.--.- "}, {".", ".-.-.- "}, {"?", "..--.. "}, {";", "-.-.-. "}, {"/", "-..-. "}, {"-", "..--.- "}, {")", "---.. "}, {"=", "-...- "}, {"@", ".--.-. "}, {"\"", ".-..-."}, {"+", ".-.-. "}, {" ", "/"}}; final static Map<Character, String> map = new HashMap<>(); static { for (String[] pair : code) map.put(pair[0].charAt(0), pair[1].trim()); } public static void main(String[] args) { printMorse("sos"); printMorse(" Hello World!"); printMorse("Rosetta Code"); } static void printMorse(String input) { System.out.printf("%s %n", input); input = input.trim().replaceAll("[ ]+", " ").toUpperCase(); for (char c : input.toCharArray()) { String s = map.get(c); if (s != null) System.out.printf("%s ", s); } System.out.println("\n"); } }
Port the following code from MATLAB to Python with equivalent syntax and logic.
function [morseText,morseSound] = text2morse(string,playSound) string = lower(string); morseDictionary = {{' ',' '},{'',''},{'',''},{'',''},... {'',''},{'',''},{'',''},{'',''},{'',''},{'',''},... {'',''},{'',''},{'',''},{'',''},{'',''},{'',''},... {'0','-----'},{'1','.----'},{'2','..---'},{'3','...--'},... {'4','....-'},{'5','.....'},{'6','-....'},{'7','--...'},... {'8','---..'},{'9','----.'},... {'',''},{'',''},{'',''},{'',''},{'',''},{'',''},... {'',''},{'',''},{'',''},{'',''},{'',''},{'',''},... {'',''},{'',''},{'',''},{'',''},{'',''},{'',''},... {'',''},{'',''},{'',''},{'',''},{'',''},{'',''},... {'',''},{'',''},{'',''},{'',''},{'',''},{'',''},... {'',''},{'',''},{'',''},{'',''},{'',''},{'',''},... {'',''},{'',''},{'',''},... {'a','.-'},{'b','-...'},{'c','-.-.'},{'d','-..'},... {'e','.'},{'f','..-.'},{'g','--.'},{'h','....'},... {'i','..'},{'j','.---'},{'k','-.-'},{'l','.-..'},... {'m','--'},{'n','-.'},{'o','---'},{'p','.--.'},... {'q','--.-'},{'r','.-.'},{'s','...'},{'t','-'},... {'u','..-'},{'v','...-'},{'w','.--'},{'x','-..-'},... {'y','-.--'},{'z','--..'}}; morseText = arrayfun(@(x)[morseDictionary{x}{2} '|'],(string - 31),'UniformOutput',false); morseText = cell2mat(morseText); morseText(end) = []; SamplingFrequency = 8192; ditLength = .1; dit = (0:1/SamplingFrequency:ditLength); dah = (0:1/SamplingFrequency:3*ditLength); dit = sin(3520*dit); dah = sin(3520*dah); silent = zeros(1,length(dit)); morseTiming = {{'.',[dit silent]},{'-',[dah silent]},{'|',[silent silent]},{' ',[silent silent]}}; morseSound = []; for i = (1:length(morseText)) cellNum = find(cellfun(@(x)(x{1}==morseText(i)),morseTiming)); morseSound = [morseSound morseTiming{cellNum}{2}]; end morseSound(end-length(silent):end) = []; if(playSound) sound(morseSound,SamplingFrequency); end end
import time, winsound char2morse = { "!": "---.", "\"": ".-..-.", "$": "...-..-", "'": ".----.", "(": "-.--.", ")": "-.--.-", "+": ".-.-.", ",": "--..--", "-": "-....-", ".": ".-.-.-", "/": "-..-.", "0": "-----", "1": ".----", "2": "..---", "3": "...--", "4": "....-", "5": ".....", "6": "-....", "7": "--...", "8": "---..", "9": "----.", ":": "---...", ";": "-.-.-.", "=": "-...-", "?": "..--..", "@": ".--.-.", "A": ".-", "B": "-...", "C": "-.-.", "D": "-..", "E": ".", "F": "..-.", "G": "--.", "H": "....", "I": "..", "J": ".---", "K": "-.-", "L": ".-..", "M": "--", "N": "-.", "O": "---", "P": ".--.", "Q": "--.-", "R": ".-.", "S": "...", "T": "-", "U": "..-", "V": "...-", "W": ".--", "X": "-..-", "Y": "-.--", "Z": "--..", "[": "-.--.", "]": "-.--.-", "_": "..--.-", } e = 50 f = 1280 chargap = 1 wordgap = 7 def gap(n=1): time.sleep(n * e / 1000) off = gap def on(n=1): winsound.Beep(f, n * e) def dit(): on(); off() def dah(): on(3); off() def bloop(n=3): winsound.Beep(f//2, n * e) def windowsmorse(text): for word in text.strip().upper().split(): for char in word: for element in char2morse.get(char, '?'): if element == '-': dah() elif element == '.': dit() else: bloop() gap(chargap) gap(wordgap) while True: windowsmorse(input('A string to change into morse: '))
Change the following MATLAB code into VB without altering its purpose.
function [morseText,morseSound] = text2morse(string,playSound) string = lower(string); morseDictionary = {{' ',' '},{'',''},{'',''},{'',''},... {'',''},{'',''},{'',''},{'',''},{'',''},{'',''},... {'',''},{'',''},{'',''},{'',''},{'',''},{'',''},... {'0','-----'},{'1','.----'},{'2','..---'},{'3','...--'},... {'4','....-'},{'5','.....'},{'6','-....'},{'7','--...'},... {'8','---..'},{'9','----.'},... {'',''},{'',''},{'',''},{'',''},{'',''},{'',''},... {'',''},{'',''},{'',''},{'',''},{'',''},{'',''},... {'',''},{'',''},{'',''},{'',''},{'',''},{'',''},... {'',''},{'',''},{'',''},{'',''},{'',''},{'',''},... {'',''},{'',''},{'',''},{'',''},{'',''},{'',''},... {'',''},{'',''},{'',''},{'',''},{'',''},{'',''},... {'',''},{'',''},{'',''},... {'a','.-'},{'b','-...'},{'c','-.-.'},{'d','-..'},... {'e','.'},{'f','..-.'},{'g','--.'},{'h','....'},... {'i','..'},{'j','.---'},{'k','-.-'},{'l','.-..'},... {'m','--'},{'n','-.'},{'o','---'},{'p','.--.'},... {'q','--.-'},{'r','.-.'},{'s','...'},{'t','-'},... {'u','..-'},{'v','...-'},{'w','.--'},{'x','-..-'},... {'y','-.--'},{'z','--..'}}; morseText = arrayfun(@(x)[morseDictionary{x}{2} '|'],(string - 31),'UniformOutput',false); morseText = cell2mat(morseText); morseText(end) = []; SamplingFrequency = 8192; ditLength = .1; dit = (0:1/SamplingFrequency:ditLength); dah = (0:1/SamplingFrequency:3*ditLength); dit = sin(3520*dit); dah = sin(3520*dah); silent = zeros(1,length(dit)); morseTiming = {{'.',[dit silent]},{'-',[dah silent]},{'|',[silent silent]},{' ',[silent silent]}}; morseSound = []; for i = (1:length(morseText)) cellNum = find(cellfun(@(x)(x{1}==morseText(i)),morseTiming)); morseSound = [morseSound morseTiming{cellNum}{2}]; end morseSound(end-length(silent):end) = []; if(playSound) sound(morseSound,SamplingFrequency); end end
Option Explicit Private Declare Function Beep Lib "kernel32" (ByVal dwFreq As Long, ByVal dwDuration As Long) As Long Private Declare Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As Long) Private Const MORSE_ALPHA As String = ".-,-...,-.-.,-..,.,..-.,--.,....,..,.---,-.-,.-..,--,-.,---,.--.,--.-,.-.,...,-,..-,...-,.--,-..-,-.--,--.." Private Const MORSE_NUMERIC As String = "-----,.----,..---,...--,....-,.....,-....,--...,---..,----." Private Const ONE_UNIT As Integer = 100 Private Const BEEP_DOT As Integer = ONE_UNIT Private Const BEEP_DASH As Integer = 3 * ONE_UNIT Private Const BEEP_OTHER As Integer = 7 * ONE_UNIT Private Const DELAY As Integer = ONE_UNIT Private Const LETTERS_DELAY As Integer = 3 * ONE_UNIT Private Const SPACE_DELAY As Integer = 7 * ONE_UNIT Private Const FREQUENCY_CHARS As Integer = 1200 Private Const FREQUENCY_OTHERCHARS As Integer = 400 Sub Main() Dim p$, temp$ p = ToMorse("Hel/lo 123 world") temp = Replace(p, "+", "") Debug.Print Replace(temp, "_", "") PlayMorse p End Sub Private Function ToMorse(s As String) As String Dim i&, t$, j& s = UCase(s) For i = 1 To Len(s) j = Asc(Mid(s, i, 1)) Select Case j Case 65 To 90 t = t & Split(MORSE_ALPHA, ",")(j - 65) & "+" Case 48 To 57 t = t & Split(MORSE_NUMERIC, ",")(j - 48) & "+" Case 32 t = t & " " & "+" Case Else t = t & "_" & "+" End Select Next i ToMorse = t End Function Private Sub PlayMorse(s As String) Dim i& For i = 1 To Len(s) Select Case Mid(s, i, 1) Case ".": Beep FREQUENCY_CHARS, BEEP_DOT Case "-": Beep FREQUENCY_CHARS, BEEP_DASH Case "_": Beep FREQUENCY_OTHERCHARS, BEEP_OTHER Case "+": Sleep LETTERS_DELAY Case " ": Sleep SPACE_DELAY End Select Sleep DELAY Next i End Sub
Rewrite the snippet below in Go so it works the same as the original MATLAB code.
function [morseText,morseSound] = text2morse(string,playSound) string = lower(string); morseDictionary = {{' ',' '},{'',''},{'',''},{'',''},... {'',''},{'',''},{'',''},{'',''},{'',''},{'',''},... {'',''},{'',''},{'',''},{'',''},{'',''},{'',''},... {'0','-----'},{'1','.----'},{'2','..---'},{'3','...--'},... {'4','....-'},{'5','.....'},{'6','-....'},{'7','--...'},... {'8','---..'},{'9','----.'},... {'',''},{'',''},{'',''},{'',''},{'',''},{'',''},... {'',''},{'',''},{'',''},{'',''},{'',''},{'',''},... {'',''},{'',''},{'',''},{'',''},{'',''},{'',''},... {'',''},{'',''},{'',''},{'',''},{'',''},{'',''},... {'',''},{'',''},{'',''},{'',''},{'',''},{'',''},... {'',''},{'',''},{'',''},{'',''},{'',''},{'',''},... {'',''},{'',''},{'',''},... {'a','.-'},{'b','-...'},{'c','-.-.'},{'d','-..'},... {'e','.'},{'f','..-.'},{'g','--.'},{'h','....'},... {'i','..'},{'j','.---'},{'k','-.-'},{'l','.-..'},... {'m','--'},{'n','-.'},{'o','---'},{'p','.--.'},... {'q','--.-'},{'r','.-.'},{'s','...'},{'t','-'},... {'u','..-'},{'v','...-'},{'w','.--'},{'x','-..-'},... {'y','-.--'},{'z','--..'}}; morseText = arrayfun(@(x)[morseDictionary{x}{2} '|'],(string - 31),'UniformOutput',false); morseText = cell2mat(morseText); morseText(end) = []; SamplingFrequency = 8192; ditLength = .1; dit = (0:1/SamplingFrequency:ditLength); dah = (0:1/SamplingFrequency:3*ditLength); dit = sin(3520*dit); dah = sin(3520*dah); silent = zeros(1,length(dit)); morseTiming = {{'.',[dit silent]},{'-',[dah silent]},{'|',[silent silent]},{' ',[silent silent]}}; morseSound = []; for i = (1:length(morseText)) cellNum = find(cellfun(@(x)(x{1}==morseText(i)),morseTiming)); morseSound = [morseSound morseTiming{cellNum}{2}]; end morseSound(end-length(silent):end) = []; if(playSound) sound(morseSound,SamplingFrequency); end end
package main import ( "flag" "fmt" "log" "regexp" "strings" "syscall" "time" "unicode" ) type key struct { duration int on bool sym string } var ( runeToKeys = map[rune][]key{} interCharGap = []key{{1, false, ""}} punctGap = []key{{7, false, " / "}} charGap = []key{{3, false, " "}} wordGap = []key{{7, false, " / "}} ) const rawMorse = ` A:.- J:.--- S:... 1:.---- .:.-.-.-  ::---... B:-... K:-.- T:- 2:..--- ,:--..--  ;:-.-.-. C:-.-. L:.-.. U:..- 3:...--  ?:..--.. =:-...- D:-.. M:-- V:...- 4:....- ':.----. +:.-.-. E:. N:-. W:.-- 5:.....  !:-.-.-- -:-....- F:..-. O:--- X:-..- 6:-.... /:-..-. _:..--.- G:--. P:.--. Y:-.-- 7:--... (:-.--. ":.-..-. H:.... Q:--.- Z:--.. 8:---.. ):-.--.- $:...-..- I:.. R:.-. 0:----- 9:----. &:.-... @:.--.-. ` func init() { r := regexp.MustCompile("([^ ]):([.-]+)") for _, m := range r.FindAllStringSubmatch(rawMorse, -1) { c := m[1][0] keys := []key{} for i, dd := range m[2] { if i > 0 { keys = append(keys, interCharGap...) } if dd == '.' { keys = append(keys, key{1, true, "."}) } else if dd == '-' { keys = append(keys, key{3, true, "-"}) } else { log.Fatalf("found %c in morse for %c", dd, c) } runeToKeys[rune(c)] = keys runeToKeys[unicode.ToLower(rune(c))] = keys } } } func MorseKeys(in string) ([]key, error) { afterWord := false afterChar := false result := []key{} for _, c := range in { if unicode.IsSpace(c) { afterWord = true continue } morse, ok := runeToKeys[c] if !ok { return nil, fmt.Errorf("can't translate %c to morse", c) } if unicode.IsPunct(c) && afterChar { result = append(result, punctGap...) } else if afterWord { result = append(result, wordGap...) } else if afterChar { result = append(result, charGap...) } result = append(result, morse...) afterChar = true afterWord = false } return result, nil } func main() { var ditDuration time.Duration flag.DurationVar(&ditDuration, "d", 40*time.Millisecond, "length of dit") flag.Parse() in := "hello world." if len(flag.Args()) > 1 { in = strings.Join(flag.Args(), " ") } keys, err := MorseKeys(in) if err != nil { log.Fatalf("failed to translate: %s", err) } for _, k := range keys { if k.on { if err := note(true); err != nil { log.Fatalf("failed to play note: %s", err) } } fmt.Print(k.sym) time.Sleep(ditDuration * time.Duration(k.duration)) if k.on { if err := note(false); err != nil { log.Fatalf("failed to stop note: %s", err) } } } fmt.Println() } var consoleFD uintptr func init() { fd, err := syscall.Open("/dev/console", syscall.O_WRONLY, 0) if err != nil { log.Fatalf("failed to get console device: %s", err) } consoleFD = uintptr(fd) } const KIOCSOUND = 0x4B2F const clockTickRate = 1193180 const freqHz = 600 func note(on bool) error { arg := uintptr(0) if on { arg = clockTickRate / freqHz } _, _, errno := syscall.Syscall(syscall.SYS_IOCTL, consoleFD, KIOCSOUND, arg) if errno != 0 { return errno } return nil }
Convert this Nim block to C, preserving its control flow and logic.
import os, strutils, tables const Morse = {'A': ".-", 'B': "-...", 'C': "-.-.", 'D': "-..", 'E': ".", 'F': "..-.", 'G': "--.", 'H': "....", 'I': "..", 'J': ".---", 'K': "-.-", 'L': ".-..", 'M': "--", 'N': "-.", 'O': "---", 'P': ".--.", 'Q': "--.-", 'R': ".-.", 'S': "...", 'T': "-", 'U': "..-", 'V': "...-", 'W': ".--", 'X': "-..-", 'Y': "-.--", 'Z': "--..", '0': "-----", '1': ".----", '2': "..---", '3': "...--", '4': "....-", '5': ".....", '6': "-....", '7': "--...", '8': "---..", '9': "----.", '.': ".-.-.-", ',': "--..--", '?': "..--..", '\'': ".----.", '!': "-.-.--", '/': "-..-.", '(': "-.--.", ')': "-.--.-", '&': ".-...", ':': "---...", ';': "-.-.-.", '=': "-...-", '+': ".-.-.", '-': "-....-", '_': "..--.-", '"': ".-..-.", '$': "...-..-", '@': ".--.-."}.toTable proc morse(s: string): string = var r: seq[string] for c in s: r.add Morse.getOrDefault(c.toUpperAscii, "") result = r.join(" ") var m: seq[string] for arg in commandLineParams(): m.add morse(arg) echo m.join(" ")
#include <ctype.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #define BIND(A,L,H) ((L)<(A)?(A)<(H)?(A):(H):(L)) char dih[50],dah[50],medium[30],word[30], *dd[2] = {dih,dah}; const char *ascii = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789.,?'!/()&:;=+-_\"$@", *itu[] = { "13","3111","3131","311","1","1131","331","1111","11","1333","313","1311","33","31","333","1331","3313","131","111","3","113","1113","133","3113","3133","3311","33333","13333","11333","11133","11113","11111","31111","33111","33311","33331","131313","331133","113311","133331","313133","31131","31331","313313","13111","333111","313131","31113","13131","311113","113313","131131","1113113","133131" }; void append(char*s,const char*morse) { for (; *morse; ++morse) strcat(s,dd['3'==*morse]); strcat(s,medium); } char*translate(const char*i,char*o) { const char*pc; sprintf(o,"beep"); for (; *i; ++i) if (NULL == (pc = strchr(ascii,toupper(*i)))) strcat(o,word); else append(o,itu[pc-ascii]); strcat(o,word); return o; } int main(int ac,char*av[]) { char sin[73],sout[100000]; int dit = 100; if (1 < ac) { if (strlen(av[1]) != strspn(av[1],"0123456789")) return 0*fprintf(stderr,"use: %s [duration] dit in ms, default %d\n",*av,dit); dit = BIND(atoi(av[1]),1,1000); } sprintf(dah," -n -f 440 -l %d -D %d",3*dit,dit); sprintf(dih," -n -f 440 -l %d -D %d",dit,dit); sprintf(medium," -n -D %d",(3-1)*dit); sprintf(word," -n -D %d",(7-(3-1)-1)*dit); while (NULL != fgets(sin,72,stdin)) puts(translate(sin,sout)); return 0; }
Produce a functionally identical C# code for the snippet given in Nim.
import os, strutils, tables const Morse = {'A': ".-", 'B': "-...", 'C': "-.-.", 'D': "-..", 'E': ".", 'F': "..-.", 'G': "--.", 'H': "....", 'I': "..", 'J': ".---", 'K': "-.-", 'L': ".-..", 'M': "--", 'N': "-.", 'O': "---", 'P': ".--.", 'Q': "--.-", 'R': ".-.", 'S': "...", 'T': "-", 'U': "..-", 'V': "...-", 'W': ".--", 'X': "-..-", 'Y': "-.--", 'Z': "--..", '0': "-----", '1': ".----", '2': "..---", '3': "...--", '4': "....-", '5': ".....", '6': "-....", '7': "--...", '8': "---..", '9': "----.", '.': ".-.-.-", ',': "--..--", '?': "..--..", '\'': ".----.", '!': "-.-.--", '/': "-..-.", '(': "-.--.", ')': "-.--.-", '&': ".-...", ':': "---...", ';': "-.-.-.", '=': "-...-", '+': ".-.-.", '-': "-....-", '_': "..--.-", '"': ".-..-.", '$': "...-..-", '@': ".--.-."}.toTable proc morse(s: string): string = var r: seq[string] for c in s: r.add Morse.getOrDefault(c.toUpperAscii, "") result = r.join(" ") var m: seq[string] for arg in commandLineParams(): m.add morse(arg) echo m.join(" ")
using System; using System.Collections.Generic; namespace Morse { class Morse { static void Main(string[] args) { string word = "sos"; Dictionary<string, string> Codes = new Dictionary<string, string> { {"a", ".- "}, {"b", "-... "}, {"c", "-.-. "}, {"d", "-.. "}, {"e", ". "}, {"f", "..-. "}, {"g", "--. "}, {"h", ".... "}, {"i", ".. "}, {"j", ".--- "}, {"k", "-.- "}, {"l", ".-.. "}, {"m", "-- "}, {"n", "-. "}, {"o", "--- "}, {"p", ".--. "}, {"q", "--.- "}, {"r", ".-. "}, {"s", "... "}, {"t", "- "}, {"u", "..- "}, {"v", "...- "}, {"w", ".-- "}, {"x", "-..- "}, {"y", "-.-- "}, {"z", "--.. "}, {"0", "-----"}, {"1", ".----"}, {"2", "..---"}, {"3", "...--"}, {"4", "....-"}, {"5", "....."}, {"6", "-...."}, {"7", "--..."}, {"8", "---.."}, {"9", "----."} }; foreach (char c in word.ToCharArray()) { string rslt = Codes[c.ToString()].Trim(); foreach (char c2 in rslt.ToCharArray()) { if (c2 == '.') Console.Beep(1000, 250); else Console.Beep(1000, 750); } System.Threading.Thread.Sleep(50); } } } }
Rewrite the snippet below in Java so it works the same as the original Nim code.
import os, strutils, tables const Morse = {'A': ".-", 'B': "-...", 'C': "-.-.", 'D': "-..", 'E': ".", 'F': "..-.", 'G': "--.", 'H': "....", 'I': "..", 'J': ".---", 'K': "-.-", 'L': ".-..", 'M': "--", 'N': "-.", 'O': "---", 'P': ".--.", 'Q': "--.-", 'R': ".-.", 'S': "...", 'T': "-", 'U': "..-", 'V': "...-", 'W': ".--", 'X': "-..-", 'Y': "-.--", 'Z': "--..", '0': "-----", '1': ".----", '2': "..---", '3': "...--", '4': "....-", '5': ".....", '6': "-....", '7': "--...", '8': "---..", '9': "----.", '.': ".-.-.-", ',': "--..--", '?': "..--..", '\'': ".----.", '!': "-.-.--", '/': "-..-.", '(': "-.--.", ')': "-.--.-", '&': ".-...", ':': "---...", ';': "-.-.-.", '=': "-...-", '+': ".-.-.", '-': "-....-", '_': "..--.-", '"': ".-..-.", '$': "...-..-", '@': ".--.-."}.toTable proc morse(s: string): string = var r: seq[string] for c in s: r.add Morse.getOrDefault(c.toUpperAscii, "") result = r.join(" ") var m: seq[string] for arg in commandLineParams(): m.add morse(arg) echo m.join(" ")
import java.util.*; public class MorseCode { final static String[][] code = { {"A", ".- "}, {"B", "-... "}, {"C", "-.-. "}, {"D", "-.. "}, {"E", ". "}, {"F", "..-. "}, {"G", "--. "}, {"H", ".... "}, {"I", ".. "}, {"J", ".--- "}, {"K", "-.- "}, {"L", ".-.. "}, {"M", "-- "}, {"N", "-. "}, {"O", "--- "}, {"P", ".--. "}, {"Q", "--.- "}, {"R", ".-. "}, {"S", "... "}, {"T", "- "}, {"U", "..- "}, {"V", "...- "}, {"W", ".- - "}, {"X", "-..- "}, {"Y", "-.-- "}, {"Z", "--.. "}, {"0", "----- "}, {"1", ".---- "}, {"2", "..--- "}, {"3", "...-- "}, {"4", "....- "}, {"5", "..... "}, {"6", "-.... "}, {"7", "--... "}, {"8", "---.. "}, {"9", "----. "}, {"'", ".----. "}, {":", "---... "}, {",", "--..-- "}, {"-", "-....- "}, {"(", "-.--.- "}, {".", ".-.-.- "}, {"?", "..--.. "}, {";", "-.-.-. "}, {"/", "-..-. "}, {"-", "..--.- "}, {")", "---.. "}, {"=", "-...- "}, {"@", ".--.-. "}, {"\"", ".-..-."}, {"+", ".-.-. "}, {" ", "/"}}; final static Map<Character, String> map = new HashMap<>(); static { for (String[] pair : code) map.put(pair[0].charAt(0), pair[1].trim()); } public static void main(String[] args) { printMorse("sos"); printMorse(" Hello World!"); printMorse("Rosetta Code"); } static void printMorse(String input) { System.out.printf("%s %n", input); input = input.trim().replaceAll("[ ]+", " ").toUpperCase(); for (char c : input.toCharArray()) { String s = map.get(c); if (s != null) System.out.printf("%s ", s); } System.out.println("\n"); } }
Ensure the translated Python code behaves exactly like the original Nim snippet.
import os, strutils, tables const Morse = {'A': ".-", 'B': "-...", 'C': "-.-.", 'D': "-..", 'E': ".", 'F': "..-.", 'G': "--.", 'H': "....", 'I': "..", 'J': ".---", 'K': "-.-", 'L': ".-..", 'M': "--", 'N': "-.", 'O': "---", 'P': ".--.", 'Q': "--.-", 'R': ".-.", 'S': "...", 'T': "-", 'U': "..-", 'V': "...-", 'W': ".--", 'X': "-..-", 'Y': "-.--", 'Z': "--..", '0': "-----", '1': ".----", '2': "..---", '3': "...--", '4': "....-", '5': ".....", '6': "-....", '7': "--...", '8': "---..", '9': "----.", '.': ".-.-.-", ',': "--..--", '?': "..--..", '\'': ".----.", '!': "-.-.--", '/': "-..-.", '(': "-.--.", ')': "-.--.-", '&': ".-...", ':': "---...", ';': "-.-.-.", '=': "-...-", '+': ".-.-.", '-': "-....-", '_': "..--.-", '"': ".-..-.", '$': "...-..-", '@': ".--.-."}.toTable proc morse(s: string): string = var r: seq[string] for c in s: r.add Morse.getOrDefault(c.toUpperAscii, "") result = r.join(" ") var m: seq[string] for arg in commandLineParams(): m.add morse(arg) echo m.join(" ")
import time, winsound char2morse = { "!": "---.", "\"": ".-..-.", "$": "...-..-", "'": ".----.", "(": "-.--.", ")": "-.--.-", "+": ".-.-.", ",": "--..--", "-": "-....-", ".": ".-.-.-", "/": "-..-.", "0": "-----", "1": ".----", "2": "..---", "3": "...--", "4": "....-", "5": ".....", "6": "-....", "7": "--...", "8": "---..", "9": "----.", ":": "---...", ";": "-.-.-.", "=": "-...-", "?": "..--..", "@": ".--.-.", "A": ".-", "B": "-...", "C": "-.-.", "D": "-..", "E": ".", "F": "..-.", "G": "--.", "H": "....", "I": "..", "J": ".---", "K": "-.-", "L": ".-..", "M": "--", "N": "-.", "O": "---", "P": ".--.", "Q": "--.-", "R": ".-.", "S": "...", "T": "-", "U": "..-", "V": "...-", "W": ".--", "X": "-..-", "Y": "-.--", "Z": "--..", "[": "-.--.", "]": "-.--.-", "_": "..--.-", } e = 50 f = 1280 chargap = 1 wordgap = 7 def gap(n=1): time.sleep(n * e / 1000) off = gap def on(n=1): winsound.Beep(f, n * e) def dit(): on(); off() def dah(): on(3); off() def bloop(n=3): winsound.Beep(f//2, n * e) def windowsmorse(text): for word in text.strip().upper().split(): for char in word: for element in char2morse.get(char, '?'): if element == '-': dah() elif element == '.': dit() else: bloop() gap(chargap) gap(wordgap) while True: windowsmorse(input('A string to change into morse: '))
Rewrite this program in VB while keeping its functionality equivalent to the Nim version.
import os, strutils, tables const Morse = {'A': ".-", 'B': "-...", 'C': "-.-.", 'D': "-..", 'E': ".", 'F': "..-.", 'G': "--.", 'H': "....", 'I': "..", 'J': ".---", 'K': "-.-", 'L': ".-..", 'M': "--", 'N': "-.", 'O': "---", 'P': ".--.", 'Q': "--.-", 'R': ".-.", 'S': "...", 'T': "-", 'U': "..-", 'V': "...-", 'W': ".--", 'X': "-..-", 'Y': "-.--", 'Z': "--..", '0': "-----", '1': ".----", '2': "..---", '3': "...--", '4': "....-", '5': ".....", '6': "-....", '7': "--...", '8': "---..", '9': "----.", '.': ".-.-.-", ',': "--..--", '?': "..--..", '\'': ".----.", '!': "-.-.--", '/': "-..-.", '(': "-.--.", ')': "-.--.-", '&': ".-...", ':': "---...", ';': "-.-.-.", '=': "-...-", '+': ".-.-.", '-': "-....-", '_': "..--.-", '"': ".-..-.", '$': "...-..-", '@': ".--.-."}.toTable proc morse(s: string): string = var r: seq[string] for c in s: r.add Morse.getOrDefault(c.toUpperAscii, "") result = r.join(" ") var m: seq[string] for arg in commandLineParams(): m.add morse(arg) echo m.join(" ")
Option Explicit Private Declare Function Beep Lib "kernel32" (ByVal dwFreq As Long, ByVal dwDuration As Long) As Long Private Declare Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As Long) Private Const MORSE_ALPHA As String = ".-,-...,-.-.,-..,.,..-.,--.,....,..,.---,-.-,.-..,--,-.,---,.--.,--.-,.-.,...,-,..-,...-,.--,-..-,-.--,--.." Private Const MORSE_NUMERIC As String = "-----,.----,..---,...--,....-,.....,-....,--...,---..,----." Private Const ONE_UNIT As Integer = 100 Private Const BEEP_DOT As Integer = ONE_UNIT Private Const BEEP_DASH As Integer = 3 * ONE_UNIT Private Const BEEP_OTHER As Integer = 7 * ONE_UNIT Private Const DELAY As Integer = ONE_UNIT Private Const LETTERS_DELAY As Integer = 3 * ONE_UNIT Private Const SPACE_DELAY As Integer = 7 * ONE_UNIT Private Const FREQUENCY_CHARS As Integer = 1200 Private Const FREQUENCY_OTHERCHARS As Integer = 400 Sub Main() Dim p$, temp$ p = ToMorse("Hel/lo 123 world") temp = Replace(p, "+", "") Debug.Print Replace(temp, "_", "") PlayMorse p End Sub Private Function ToMorse(s As String) As String Dim i&, t$, j& s = UCase(s) For i = 1 To Len(s) j = Asc(Mid(s, i, 1)) Select Case j Case 65 To 90 t = t & Split(MORSE_ALPHA, ",")(j - 65) & "+" Case 48 To 57 t = t & Split(MORSE_NUMERIC, ",")(j - 48) & "+" Case 32 t = t & " " & "+" Case Else t = t & "_" & "+" End Select Next i ToMorse = t End Function Private Sub PlayMorse(s As String) Dim i& For i = 1 To Len(s) Select Case Mid(s, i, 1) Case ".": Beep FREQUENCY_CHARS, BEEP_DOT Case "-": Beep FREQUENCY_CHARS, BEEP_DASH Case "_": Beep FREQUENCY_OTHERCHARS, BEEP_OTHER Case "+": Sleep LETTERS_DELAY Case " ": Sleep SPACE_DELAY End Select Sleep DELAY Next i End Sub
Translate this program into Go but keep the logic exactly as in Nim.
import os, strutils, tables const Morse = {'A': ".-", 'B': "-...", 'C': "-.-.", 'D': "-..", 'E': ".", 'F': "..-.", 'G': "--.", 'H': "....", 'I': "..", 'J': ".---", 'K': "-.-", 'L': ".-..", 'M': "--", 'N': "-.", 'O': "---", 'P': ".--.", 'Q': "--.-", 'R': ".-.", 'S': "...", 'T': "-", 'U': "..-", 'V': "...-", 'W': ".--", 'X': "-..-", 'Y': "-.--", 'Z': "--..", '0': "-----", '1': ".----", '2': "..---", '3': "...--", '4': "....-", '5': ".....", '6': "-....", '7': "--...", '8': "---..", '9': "----.", '.': ".-.-.-", ',': "--..--", '?': "..--..", '\'': ".----.", '!': "-.-.--", '/': "-..-.", '(': "-.--.", ')': "-.--.-", '&': ".-...", ':': "---...", ';': "-.-.-.", '=': "-...-", '+': ".-.-.", '-': "-....-", '_': "..--.-", '"': ".-..-.", '$': "...-..-", '@': ".--.-."}.toTable proc morse(s: string): string = var r: seq[string] for c in s: r.add Morse.getOrDefault(c.toUpperAscii, "") result = r.join(" ") var m: seq[string] for arg in commandLineParams(): m.add morse(arg) echo m.join(" ")
package main import ( "flag" "fmt" "log" "regexp" "strings" "syscall" "time" "unicode" ) type key struct { duration int on bool sym string } var ( runeToKeys = map[rune][]key{} interCharGap = []key{{1, false, ""}} punctGap = []key{{7, false, " / "}} charGap = []key{{3, false, " "}} wordGap = []key{{7, false, " / "}} ) const rawMorse = ` A:.- J:.--- S:... 1:.---- .:.-.-.-  ::---... B:-... K:-.- T:- 2:..--- ,:--..--  ;:-.-.-. C:-.-. L:.-.. U:..- 3:...--  ?:..--.. =:-...- D:-.. M:-- V:...- 4:....- ':.----. +:.-.-. E:. N:-. W:.-- 5:.....  !:-.-.-- -:-....- F:..-. O:--- X:-..- 6:-.... /:-..-. _:..--.- G:--. P:.--. Y:-.-- 7:--... (:-.--. ":.-..-. H:.... Q:--.- Z:--.. 8:---.. ):-.--.- $:...-..- I:.. R:.-. 0:----- 9:----. &:.-... @:.--.-. ` func init() { r := regexp.MustCompile("([^ ]):([.-]+)") for _, m := range r.FindAllStringSubmatch(rawMorse, -1) { c := m[1][0] keys := []key{} for i, dd := range m[2] { if i > 0 { keys = append(keys, interCharGap...) } if dd == '.' { keys = append(keys, key{1, true, "."}) } else if dd == '-' { keys = append(keys, key{3, true, "-"}) } else { log.Fatalf("found %c in morse for %c", dd, c) } runeToKeys[rune(c)] = keys runeToKeys[unicode.ToLower(rune(c))] = keys } } } func MorseKeys(in string) ([]key, error) { afterWord := false afterChar := false result := []key{} for _, c := range in { if unicode.IsSpace(c) { afterWord = true continue } morse, ok := runeToKeys[c] if !ok { return nil, fmt.Errorf("can't translate %c to morse", c) } if unicode.IsPunct(c) && afterChar { result = append(result, punctGap...) } else if afterWord { result = append(result, wordGap...) } else if afterChar { result = append(result, charGap...) } result = append(result, morse...) afterChar = true afterWord = false } return result, nil } func main() { var ditDuration time.Duration flag.DurationVar(&ditDuration, "d", 40*time.Millisecond, "length of dit") flag.Parse() in := "hello world." if len(flag.Args()) > 1 { in = strings.Join(flag.Args(), " ") } keys, err := MorseKeys(in) if err != nil { log.Fatalf("failed to translate: %s", err) } for _, k := range keys { if k.on { if err := note(true); err != nil { log.Fatalf("failed to play note: %s", err) } } fmt.Print(k.sym) time.Sleep(ditDuration * time.Duration(k.duration)) if k.on { if err := note(false); err != nil { log.Fatalf("failed to stop note: %s", err) } } } fmt.Println() } var consoleFD uintptr func init() { fd, err := syscall.Open("/dev/console", syscall.O_WRONLY, 0) if err != nil { log.Fatalf("failed to get console device: %s", err) } consoleFD = uintptr(fd) } const KIOCSOUND = 0x4B2F const clockTickRate = 1193180 const freqHz = 600 func note(on bool) error { arg := uintptr(0) if on { arg = clockTickRate / freqHz } _, _, errno := syscall.Syscall(syscall.SYS_IOCTL, consoleFD, KIOCSOUND, arg) if errno != 0 { return errno } return nil }
Write a version of this OCaml function in C with identical behavior.
let codes = [ 'a', ".-"; 'b', "-..."; 'c', "-.-."; 'd', "-.."; 'e', "."; 'f', "..-."; 'g', "--."; 'h', "...."; 'i', ".."; 'j', ".---"; 'k', "-.-"; 'l', ".-.."; 'm', "--"; 'n', "-."; 'o', "---"; 'p', ".--."; 'q', "--.-"; 'r', ".-."; 's', "..."; 't', "-"; 'u', "..-"; 'v', "...-"; 'w', ".--"; 'x', "-..-"; 'y', "-.--"; 'z', "--.."; '0', "-----"; '1', ".----"; '2', "..---"; '3', "...--"; '4', "....-"; '5', "....."; '6', "-...."; '7', "--..."; '8', "---.."; '9', "----."; ] let oc = open_out "/dev/dsp" let bip u = for i = 0 to pred u do let j = sin(0.6 *. (float i)) in let k = ((j +. 1.0) /. 2.0) *. 127.0 in output_byte oc (truncate k) done let gap u = for i = 0 to pred u do output_byte oc 0 done let morse = let u = 1000 in let u2 = u * 2 in let u3 = u * 3 in let u6 = u * 6 in String.iter (function | ' ' -> gap u6 | 'a'..'z' | 'A'..'Z' | '0'..'9' as c -> let s = List.assoc c codes in String.iter (function '.' -> bip u; gap u | '-' -> bip u3; gap u | _ -> assert false ) s; gap u2 | _ -> prerr_endline "unknown char") let () = morse "rosettacode morse"
#include <ctype.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #define BIND(A,L,H) ((L)<(A)?(A)<(H)?(A):(H):(L)) char dih[50],dah[50],medium[30],word[30], *dd[2] = {dih,dah}; const char *ascii = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789.,?'!/()&:;=+-_\"$@", *itu[] = { "13","3111","3131","311","1","1131","331","1111","11","1333","313","1311","33","31","333","1331","3313","131","111","3","113","1113","133","3113","3133","3311","33333","13333","11333","11133","11113","11111","31111","33111","33311","33331","131313","331133","113311","133331","313133","31131","31331","313313","13111","333111","313131","31113","13131","311113","113313","131131","1113113","133131" }; void append(char*s,const char*morse) { for (; *morse; ++morse) strcat(s,dd['3'==*morse]); strcat(s,medium); } char*translate(const char*i,char*o) { const char*pc; sprintf(o,"beep"); for (; *i; ++i) if (NULL == (pc = strchr(ascii,toupper(*i)))) strcat(o,word); else append(o,itu[pc-ascii]); strcat(o,word); return o; } int main(int ac,char*av[]) { char sin[73],sout[100000]; int dit = 100; if (1 < ac) { if (strlen(av[1]) != strspn(av[1],"0123456789")) return 0*fprintf(stderr,"use: %s [duration] dit in ms, default %d\n",*av,dit); dit = BIND(atoi(av[1]),1,1000); } sprintf(dah," -n -f 440 -l %d -D %d",3*dit,dit); sprintf(dih," -n -f 440 -l %d -D %d",dit,dit); sprintf(medium," -n -D %d",(3-1)*dit); sprintf(word," -n -D %d",(7-(3-1)-1)*dit); while (NULL != fgets(sin,72,stdin)) puts(translate(sin,sout)); return 0; }
Preserve the algorithm and functionality while converting the code from OCaml to C#.
let codes = [ 'a', ".-"; 'b', "-..."; 'c', "-.-."; 'd', "-.."; 'e', "."; 'f', "..-."; 'g', "--."; 'h', "...."; 'i', ".."; 'j', ".---"; 'k', "-.-"; 'l', ".-.."; 'm', "--"; 'n', "-."; 'o', "---"; 'p', ".--."; 'q', "--.-"; 'r', ".-."; 's', "..."; 't', "-"; 'u', "..-"; 'v', "...-"; 'w', ".--"; 'x', "-..-"; 'y', "-.--"; 'z', "--.."; '0', "-----"; '1', ".----"; '2', "..---"; '3', "...--"; '4', "....-"; '5', "....."; '6', "-...."; '7', "--..."; '8', "---.."; '9', "----."; ] let oc = open_out "/dev/dsp" let bip u = for i = 0 to pred u do let j = sin(0.6 *. (float i)) in let k = ((j +. 1.0) /. 2.0) *. 127.0 in output_byte oc (truncate k) done let gap u = for i = 0 to pred u do output_byte oc 0 done let morse = let u = 1000 in let u2 = u * 2 in let u3 = u * 3 in let u6 = u * 6 in String.iter (function | ' ' -> gap u6 | 'a'..'z' | 'A'..'Z' | '0'..'9' as c -> let s = List.assoc c codes in String.iter (function '.' -> bip u; gap u | '-' -> bip u3; gap u | _ -> assert false ) s; gap u2 | _ -> prerr_endline "unknown char") let () = morse "rosettacode morse"
using System; using System.Collections.Generic; namespace Morse { class Morse { static void Main(string[] args) { string word = "sos"; Dictionary<string, string> Codes = new Dictionary<string, string> { {"a", ".- "}, {"b", "-... "}, {"c", "-.-. "}, {"d", "-.. "}, {"e", ". "}, {"f", "..-. "}, {"g", "--. "}, {"h", ".... "}, {"i", ".. "}, {"j", ".--- "}, {"k", "-.- "}, {"l", ".-.. "}, {"m", "-- "}, {"n", "-. "}, {"o", "--- "}, {"p", ".--. "}, {"q", "--.- "}, {"r", ".-. "}, {"s", "... "}, {"t", "- "}, {"u", "..- "}, {"v", "...- "}, {"w", ".-- "}, {"x", "-..- "}, {"y", "-.-- "}, {"z", "--.. "}, {"0", "-----"}, {"1", ".----"}, {"2", "..---"}, {"3", "...--"}, {"4", "....-"}, {"5", "....."}, {"6", "-...."}, {"7", "--..."}, {"8", "---.."}, {"9", "----."} }; foreach (char c in word.ToCharArray()) { string rslt = Codes[c.ToString()].Trim(); foreach (char c2 in rslt.ToCharArray()) { if (c2 == '.') Console.Beep(1000, 250); else Console.Beep(1000, 750); } System.Threading.Thread.Sleep(50); } } } }
Change the following OCaml code into Java without altering its purpose.
let codes = [ 'a', ".-"; 'b', "-..."; 'c', "-.-."; 'd', "-.."; 'e', "."; 'f', "..-."; 'g', "--."; 'h', "...."; 'i', ".."; 'j', ".---"; 'k', "-.-"; 'l', ".-.."; 'm', "--"; 'n', "-."; 'o', "---"; 'p', ".--."; 'q', "--.-"; 'r', ".-."; 's', "..."; 't', "-"; 'u', "..-"; 'v', "...-"; 'w', ".--"; 'x', "-..-"; 'y', "-.--"; 'z', "--.."; '0', "-----"; '1', ".----"; '2', "..---"; '3', "...--"; '4', "....-"; '5', "....."; '6', "-...."; '7', "--..."; '8', "---.."; '9', "----."; ] let oc = open_out "/dev/dsp" let bip u = for i = 0 to pred u do let j = sin(0.6 *. (float i)) in let k = ((j +. 1.0) /. 2.0) *. 127.0 in output_byte oc (truncate k) done let gap u = for i = 0 to pred u do output_byte oc 0 done let morse = let u = 1000 in let u2 = u * 2 in let u3 = u * 3 in let u6 = u * 6 in String.iter (function | ' ' -> gap u6 | 'a'..'z' | 'A'..'Z' | '0'..'9' as c -> let s = List.assoc c codes in String.iter (function '.' -> bip u; gap u | '-' -> bip u3; gap u | _ -> assert false ) s; gap u2 | _ -> prerr_endline "unknown char") let () = morse "rosettacode morse"
import java.util.*; public class MorseCode { final static String[][] code = { {"A", ".- "}, {"B", "-... "}, {"C", "-.-. "}, {"D", "-.. "}, {"E", ". "}, {"F", "..-. "}, {"G", "--. "}, {"H", ".... "}, {"I", ".. "}, {"J", ".--- "}, {"K", "-.- "}, {"L", ".-.. "}, {"M", "-- "}, {"N", "-. "}, {"O", "--- "}, {"P", ".--. "}, {"Q", "--.- "}, {"R", ".-. "}, {"S", "... "}, {"T", "- "}, {"U", "..- "}, {"V", "...- "}, {"W", ".- - "}, {"X", "-..- "}, {"Y", "-.-- "}, {"Z", "--.. "}, {"0", "----- "}, {"1", ".---- "}, {"2", "..--- "}, {"3", "...-- "}, {"4", "....- "}, {"5", "..... "}, {"6", "-.... "}, {"7", "--... "}, {"8", "---.. "}, {"9", "----. "}, {"'", ".----. "}, {":", "---... "}, {",", "--..-- "}, {"-", "-....- "}, {"(", "-.--.- "}, {".", ".-.-.- "}, {"?", "..--.. "}, {";", "-.-.-. "}, {"/", "-..-. "}, {"-", "..--.- "}, {")", "---.. "}, {"=", "-...- "}, {"@", ".--.-. "}, {"\"", ".-..-."}, {"+", ".-.-. "}, {" ", "/"}}; final static Map<Character, String> map = new HashMap<>(); static { for (String[] pair : code) map.put(pair[0].charAt(0), pair[1].trim()); } public static void main(String[] args) { printMorse("sos"); printMorse(" Hello World!"); printMorse("Rosetta Code"); } static void printMorse(String input) { System.out.printf("%s %n", input); input = input.trim().replaceAll("[ ]+", " ").toUpperCase(); for (char c : input.toCharArray()) { String s = map.get(c); if (s != null) System.out.printf("%s ", s); } System.out.println("\n"); } }
Write a version of this OCaml function in Python with identical behavior.
let codes = [ 'a', ".-"; 'b', "-..."; 'c', "-.-."; 'd', "-.."; 'e', "."; 'f', "..-."; 'g', "--."; 'h', "...."; 'i', ".."; 'j', ".---"; 'k', "-.-"; 'l', ".-.."; 'm', "--"; 'n', "-."; 'o', "---"; 'p', ".--."; 'q', "--.-"; 'r', ".-."; 's', "..."; 't', "-"; 'u', "..-"; 'v', "...-"; 'w', ".--"; 'x', "-..-"; 'y', "-.--"; 'z', "--.."; '0', "-----"; '1', ".----"; '2', "..---"; '3', "...--"; '4', "....-"; '5', "....."; '6', "-...."; '7', "--..."; '8', "---.."; '9', "----."; ] let oc = open_out "/dev/dsp" let bip u = for i = 0 to pred u do let j = sin(0.6 *. (float i)) in let k = ((j +. 1.0) /. 2.0) *. 127.0 in output_byte oc (truncate k) done let gap u = for i = 0 to pred u do output_byte oc 0 done let morse = let u = 1000 in let u2 = u * 2 in let u3 = u * 3 in let u6 = u * 6 in String.iter (function | ' ' -> gap u6 | 'a'..'z' | 'A'..'Z' | '0'..'9' as c -> let s = List.assoc c codes in String.iter (function '.' -> bip u; gap u | '-' -> bip u3; gap u | _ -> assert false ) s; gap u2 | _ -> prerr_endline "unknown char") let () = morse "rosettacode morse"
import time, winsound char2morse = { "!": "---.", "\"": ".-..-.", "$": "...-..-", "'": ".----.", "(": "-.--.", ")": "-.--.-", "+": ".-.-.", ",": "--..--", "-": "-....-", ".": ".-.-.-", "/": "-..-.", "0": "-----", "1": ".----", "2": "..---", "3": "...--", "4": "....-", "5": ".....", "6": "-....", "7": "--...", "8": "---..", "9": "----.", ":": "---...", ";": "-.-.-.", "=": "-...-", "?": "..--..", "@": ".--.-.", "A": ".-", "B": "-...", "C": "-.-.", "D": "-..", "E": ".", "F": "..-.", "G": "--.", "H": "....", "I": "..", "J": ".---", "K": "-.-", "L": ".-..", "M": "--", "N": "-.", "O": "---", "P": ".--.", "Q": "--.-", "R": ".-.", "S": "...", "T": "-", "U": "..-", "V": "...-", "W": ".--", "X": "-..-", "Y": "-.--", "Z": "--..", "[": "-.--.", "]": "-.--.-", "_": "..--.-", } e = 50 f = 1280 chargap = 1 wordgap = 7 def gap(n=1): time.sleep(n * e / 1000) off = gap def on(n=1): winsound.Beep(f, n * e) def dit(): on(); off() def dah(): on(3); off() def bloop(n=3): winsound.Beep(f//2, n * e) def windowsmorse(text): for word in text.strip().upper().split(): for char in word: for element in char2morse.get(char, '?'): if element == '-': dah() elif element == '.': dit() else: bloop() gap(chargap) gap(wordgap) while True: windowsmorse(input('A string to change into morse: '))
Convert the following code from OCaml to VB, ensuring the logic remains intact.
let codes = [ 'a', ".-"; 'b', "-..."; 'c', "-.-."; 'd', "-.."; 'e', "."; 'f', "..-."; 'g', "--."; 'h', "...."; 'i', ".."; 'j', ".---"; 'k', "-.-"; 'l', ".-.."; 'm', "--"; 'n', "-."; 'o', "---"; 'p', ".--."; 'q', "--.-"; 'r', ".-."; 's', "..."; 't', "-"; 'u', "..-"; 'v', "...-"; 'w', ".--"; 'x', "-..-"; 'y', "-.--"; 'z', "--.."; '0', "-----"; '1', ".----"; '2', "..---"; '3', "...--"; '4', "....-"; '5', "....."; '6', "-...."; '7', "--..."; '8', "---.."; '9', "----."; ] let oc = open_out "/dev/dsp" let bip u = for i = 0 to pred u do let j = sin(0.6 *. (float i)) in let k = ((j +. 1.0) /. 2.0) *. 127.0 in output_byte oc (truncate k) done let gap u = for i = 0 to pred u do output_byte oc 0 done let morse = let u = 1000 in let u2 = u * 2 in let u3 = u * 3 in let u6 = u * 6 in String.iter (function | ' ' -> gap u6 | 'a'..'z' | 'A'..'Z' | '0'..'9' as c -> let s = List.assoc c codes in String.iter (function '.' -> bip u; gap u | '-' -> bip u3; gap u | _ -> assert false ) s; gap u2 | _ -> prerr_endline "unknown char") let () = morse "rosettacode morse"
Option Explicit Private Declare Function Beep Lib "kernel32" (ByVal dwFreq As Long, ByVal dwDuration As Long) As Long Private Declare Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As Long) Private Const MORSE_ALPHA As String = ".-,-...,-.-.,-..,.,..-.,--.,....,..,.---,-.-,.-..,--,-.,---,.--.,--.-,.-.,...,-,..-,...-,.--,-..-,-.--,--.." Private Const MORSE_NUMERIC As String = "-----,.----,..---,...--,....-,.....,-....,--...,---..,----." Private Const ONE_UNIT As Integer = 100 Private Const BEEP_DOT As Integer = ONE_UNIT Private Const BEEP_DASH As Integer = 3 * ONE_UNIT Private Const BEEP_OTHER As Integer = 7 * ONE_UNIT Private Const DELAY As Integer = ONE_UNIT Private Const LETTERS_DELAY As Integer = 3 * ONE_UNIT Private Const SPACE_DELAY As Integer = 7 * ONE_UNIT Private Const FREQUENCY_CHARS As Integer = 1200 Private Const FREQUENCY_OTHERCHARS As Integer = 400 Sub Main() Dim p$, temp$ p = ToMorse("Hel/lo 123 world") temp = Replace(p, "+", "") Debug.Print Replace(temp, "_", "") PlayMorse p End Sub Private Function ToMorse(s As String) As String Dim i&, t$, j& s = UCase(s) For i = 1 To Len(s) j = Asc(Mid(s, i, 1)) Select Case j Case 65 To 90 t = t & Split(MORSE_ALPHA, ",")(j - 65) & "+" Case 48 To 57 t = t & Split(MORSE_NUMERIC, ",")(j - 48) & "+" Case 32 t = t & " " & "+" Case Else t = t & "_" & "+" End Select Next i ToMorse = t End Function Private Sub PlayMorse(s As String) Dim i& For i = 1 To Len(s) Select Case Mid(s, i, 1) Case ".": Beep FREQUENCY_CHARS, BEEP_DOT Case "-": Beep FREQUENCY_CHARS, BEEP_DASH Case "_": Beep FREQUENCY_OTHERCHARS, BEEP_OTHER Case "+": Sleep LETTERS_DELAY Case " ": Sleep SPACE_DELAY End Select Sleep DELAY Next i End Sub
Translate this program into Go but keep the logic exactly as in OCaml.
let codes = [ 'a', ".-"; 'b', "-..."; 'c', "-.-."; 'd', "-.."; 'e', "."; 'f', "..-."; 'g', "--."; 'h', "...."; 'i', ".."; 'j', ".---"; 'k', "-.-"; 'l', ".-.."; 'm', "--"; 'n', "-."; 'o', "---"; 'p', ".--."; 'q', "--.-"; 'r', ".-."; 's', "..."; 't', "-"; 'u', "..-"; 'v', "...-"; 'w', ".--"; 'x', "-..-"; 'y', "-.--"; 'z', "--.."; '0', "-----"; '1', ".----"; '2', "..---"; '3', "...--"; '4', "....-"; '5', "....."; '6', "-...."; '7', "--..."; '8', "---.."; '9', "----."; ] let oc = open_out "/dev/dsp" let bip u = for i = 0 to pred u do let j = sin(0.6 *. (float i)) in let k = ((j +. 1.0) /. 2.0) *. 127.0 in output_byte oc (truncate k) done let gap u = for i = 0 to pred u do output_byte oc 0 done let morse = let u = 1000 in let u2 = u * 2 in let u3 = u * 3 in let u6 = u * 6 in String.iter (function | ' ' -> gap u6 | 'a'..'z' | 'A'..'Z' | '0'..'9' as c -> let s = List.assoc c codes in String.iter (function '.' -> bip u; gap u | '-' -> bip u3; gap u | _ -> assert false ) s; gap u2 | _ -> prerr_endline "unknown char") let () = morse "rosettacode morse"
package main import ( "flag" "fmt" "log" "regexp" "strings" "syscall" "time" "unicode" ) type key struct { duration int on bool sym string } var ( runeToKeys = map[rune][]key{} interCharGap = []key{{1, false, ""}} punctGap = []key{{7, false, " / "}} charGap = []key{{3, false, " "}} wordGap = []key{{7, false, " / "}} ) const rawMorse = ` A:.- J:.--- S:... 1:.---- .:.-.-.-  ::---... B:-... K:-.- T:- 2:..--- ,:--..--  ;:-.-.-. C:-.-. L:.-.. U:..- 3:...--  ?:..--.. =:-...- D:-.. M:-- V:...- 4:....- ':.----. +:.-.-. E:. N:-. W:.-- 5:.....  !:-.-.-- -:-....- F:..-. O:--- X:-..- 6:-.... /:-..-. _:..--.- G:--. P:.--. Y:-.-- 7:--... (:-.--. ":.-..-. H:.... Q:--.- Z:--.. 8:---.. ):-.--.- $:...-..- I:.. R:.-. 0:----- 9:----. &:.-... @:.--.-. ` func init() { r := regexp.MustCompile("([^ ]):([.-]+)") for _, m := range r.FindAllStringSubmatch(rawMorse, -1) { c := m[1][0] keys := []key{} for i, dd := range m[2] { if i > 0 { keys = append(keys, interCharGap...) } if dd == '.' { keys = append(keys, key{1, true, "."}) } else if dd == '-' { keys = append(keys, key{3, true, "-"}) } else { log.Fatalf("found %c in morse for %c", dd, c) } runeToKeys[rune(c)] = keys runeToKeys[unicode.ToLower(rune(c))] = keys } } } func MorseKeys(in string) ([]key, error) { afterWord := false afterChar := false result := []key{} for _, c := range in { if unicode.IsSpace(c) { afterWord = true continue } morse, ok := runeToKeys[c] if !ok { return nil, fmt.Errorf("can't translate %c to morse", c) } if unicode.IsPunct(c) && afterChar { result = append(result, punctGap...) } else if afterWord { result = append(result, wordGap...) } else if afterChar { result = append(result, charGap...) } result = append(result, morse...) afterChar = true afterWord = false } return result, nil } func main() { var ditDuration time.Duration flag.DurationVar(&ditDuration, "d", 40*time.Millisecond, "length of dit") flag.Parse() in := "hello world." if len(flag.Args()) > 1 { in = strings.Join(flag.Args(), " ") } keys, err := MorseKeys(in) if err != nil { log.Fatalf("failed to translate: %s", err) } for _, k := range keys { if k.on { if err := note(true); err != nil { log.Fatalf("failed to play note: %s", err) } } fmt.Print(k.sym) time.Sleep(ditDuration * time.Duration(k.duration)) if k.on { if err := note(false); err != nil { log.Fatalf("failed to stop note: %s", err) } } } fmt.Println() } var consoleFD uintptr func init() { fd, err := syscall.Open("/dev/console", syscall.O_WRONLY, 0) if err != nil { log.Fatalf("failed to get console device: %s", err) } consoleFD = uintptr(fd) } const KIOCSOUND = 0x4B2F const clockTickRate = 1193180 const freqHz = 600 func note(on bool) error { arg := uintptr(0) if on { arg = clockTickRate / freqHz } _, _, errno := syscall.Syscall(syscall.SYS_IOCTL, consoleFD, KIOCSOUND, arg) if errno != 0 { return errno } return nil }
Write the same algorithm in C as shown in this Pascal implementation.
PROGRAM cw; USES OpenAL, HRTimer; CONST Morse: ARRAY [32..95] OF STRING = (' ','-.-.--','.-..-.','#','...-..-','%','.-...','.----.','-.--.','-.--.-','*','.-.-.','--..--','-....-','.-.-.-','-..-.','-----','.----','..---','...--','....-','.....','-....','--...','---..','----.','---...','-.-.-.','>','-...-','<','..--..','.--.-.','.-','-...','-.-.','-..','.','..-.','--.','....','..','.---','-.-','.-..','--','-.','---','.--.','--.-','.-.','...','-','..-','...-','.--','-..-','-.--','--..','-.--.','\','-.--.-','~','..--.-'); doh = 0.4; dit = 0.05; dah = 3 * dit + doh * dit; VAR buffer : TALuint; source : TALuint; sourcepos: ARRAY [0..2] OF TALfloat= ( 0.0, 0.0, 0.0 ); sourcevel: ARRAY [0..2] OF TALfloat= ( 0.0, 0.0, 0.0 ); argv: ARRAY OF PalByte; format: TALEnum; size: TALSizei; freq: TALSizei; loop: TALInt; data: TALVoid; rewind : BOOLEAN = FALSE; t : THRTimer; msg : STRING = 'the quick brown fox jumps over the lazy dog.'; PROCEDURE PlayS(s: Extended); BEGIN StartTimer(t); AlSourcePlay(source); WHILE readseconds(t) < s DO BEGIN END; IF rewind THEN AlSourceRewind(source); AlSourceStop(source); END; PROCEDURE Pause(s: Extended); BEGIN StartTimer(t); WHILE readseconds(t) < s DO BEGIN END; END; PROCEDURE doDit; BEGIN PlayS(dit); Pause(dit); END; PROCEDURE doDah; BEGIN PlayS(dah); Pause(dit); END; FUNCTION AtoM(ch: CHAR): STRING; VAR i: Integer; u: CHAR; BEGIN u := ch; IF ch IN ['a'..'z'] THEN u := chr(ord(ch) AND $5F); result := Morse[ord(u)]; FOR i := 1 TO Length(result) DO CASE result[i] OF '.': BEGIN doDit; Write('. ') END; '-': BEGIN doDah; Write('_ ') END; END; Pause(dah); Write(' '); IF u = ' ' THEN Write(' '); END; PROCEDURE StoM(s: STRING); VAR i: Integer; BEGIN FOR i := 1 TO Length(s) DO AtoM(s[i]); END; BEGIN InitOpenAL; AlutInit(nil,argv); AlGenBuffers(1, @buffer); AlutLoadWavFile('audiocheck.net_sin_500Hz_-3dBFS_1s.wav', format, data, size, freq, loop); AlBufferData(buffer, format, data, size, freq); AlutUnloadWav(format, data, size, freq); AlGenSources(1, @source); AlSourcei ( source, AL_BUFFER, buffer); AlSourcef ( source, AL_PITCH, 1.0 ); AlSourcef ( source, AL_GAIN, 1.0 ); AlSourcefv ( source, AL_POSITION, @sourcepos); AlSourcefv ( source, AL_VELOCITY, @sourcevel); AlSourcei ( source, AL_LOOPING, AL_TRUE); StoM(msg); Pause(1.0); AlSourceRewind(source); AlSourceStop(source); AlDeleteBuffers(1, @buffer); AlDeleteSources(1, @source); AlutExit(); END.
#include <ctype.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #define BIND(A,L,H) ((L)<(A)?(A)<(H)?(A):(H):(L)) char dih[50],dah[50],medium[30],word[30], *dd[2] = {dih,dah}; const char *ascii = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789.,?'!/()&:;=+-_\"$@", *itu[] = { "13","3111","3131","311","1","1131","331","1111","11","1333","313","1311","33","31","333","1331","3313","131","111","3","113","1113","133","3113","3133","3311","33333","13333","11333","11133","11113","11111","31111","33111","33311","33331","131313","331133","113311","133331","313133","31131","31331","313313","13111","333111","313131","31113","13131","311113","113313","131131","1113113","133131" }; void append(char*s,const char*morse) { for (; *morse; ++morse) strcat(s,dd['3'==*morse]); strcat(s,medium); } char*translate(const char*i,char*o) { const char*pc; sprintf(o,"beep"); for (; *i; ++i) if (NULL == (pc = strchr(ascii,toupper(*i)))) strcat(o,word); else append(o,itu[pc-ascii]); strcat(o,word); return o; } int main(int ac,char*av[]) { char sin[73],sout[100000]; int dit = 100; if (1 < ac) { if (strlen(av[1]) != strspn(av[1],"0123456789")) return 0*fprintf(stderr,"use: %s [duration] dit in ms, default %d\n",*av,dit); dit = BIND(atoi(av[1]),1,1000); } sprintf(dah," -n -f 440 -l %d -D %d",3*dit,dit); sprintf(dih," -n -f 440 -l %d -D %d",dit,dit); sprintf(medium," -n -D %d",(3-1)*dit); sprintf(word," -n -D %d",(7-(3-1)-1)*dit); while (NULL != fgets(sin,72,stdin)) puts(translate(sin,sout)); return 0; }
Please provide an equivalent version of this Pascal code in C#.
PROGRAM cw; USES OpenAL, HRTimer; CONST Morse: ARRAY [32..95] OF STRING = (' ','-.-.--','.-..-.','#','...-..-','%','.-...','.----.','-.--.','-.--.-','*','.-.-.','--..--','-....-','.-.-.-','-..-.','-----','.----','..---','...--','....-','.....','-....','--...','---..','----.','---...','-.-.-.','>','-...-','<','..--..','.--.-.','.-','-...','-.-.','-..','.','..-.','--.','....','..','.---','-.-','.-..','--','-.','---','.--.','--.-','.-.','...','-','..-','...-','.--','-..-','-.--','--..','-.--.','\','-.--.-','~','..--.-'); doh = 0.4; dit = 0.05; dah = 3 * dit + doh * dit; VAR buffer : TALuint; source : TALuint; sourcepos: ARRAY [0..2] OF TALfloat= ( 0.0, 0.0, 0.0 ); sourcevel: ARRAY [0..2] OF TALfloat= ( 0.0, 0.0, 0.0 ); argv: ARRAY OF PalByte; format: TALEnum; size: TALSizei; freq: TALSizei; loop: TALInt; data: TALVoid; rewind : BOOLEAN = FALSE; t : THRTimer; msg : STRING = 'the quick brown fox jumps over the lazy dog.'; PROCEDURE PlayS(s: Extended); BEGIN StartTimer(t); AlSourcePlay(source); WHILE readseconds(t) < s DO BEGIN END; IF rewind THEN AlSourceRewind(source); AlSourceStop(source); END; PROCEDURE Pause(s: Extended); BEGIN StartTimer(t); WHILE readseconds(t) < s DO BEGIN END; END; PROCEDURE doDit; BEGIN PlayS(dit); Pause(dit); END; PROCEDURE doDah; BEGIN PlayS(dah); Pause(dit); END; FUNCTION AtoM(ch: CHAR): STRING; VAR i: Integer; u: CHAR; BEGIN u := ch; IF ch IN ['a'..'z'] THEN u := chr(ord(ch) AND $5F); result := Morse[ord(u)]; FOR i := 1 TO Length(result) DO CASE result[i] OF '.': BEGIN doDit; Write('. ') END; '-': BEGIN doDah; Write('_ ') END; END; Pause(dah); Write(' '); IF u = ' ' THEN Write(' '); END; PROCEDURE StoM(s: STRING); VAR i: Integer; BEGIN FOR i := 1 TO Length(s) DO AtoM(s[i]); END; BEGIN InitOpenAL; AlutInit(nil,argv); AlGenBuffers(1, @buffer); AlutLoadWavFile('audiocheck.net_sin_500Hz_-3dBFS_1s.wav', format, data, size, freq, loop); AlBufferData(buffer, format, data, size, freq); AlutUnloadWav(format, data, size, freq); AlGenSources(1, @source); AlSourcei ( source, AL_BUFFER, buffer); AlSourcef ( source, AL_PITCH, 1.0 ); AlSourcef ( source, AL_GAIN, 1.0 ); AlSourcefv ( source, AL_POSITION, @sourcepos); AlSourcefv ( source, AL_VELOCITY, @sourcevel); AlSourcei ( source, AL_LOOPING, AL_TRUE); StoM(msg); Pause(1.0); AlSourceRewind(source); AlSourceStop(source); AlDeleteBuffers(1, @buffer); AlDeleteSources(1, @source); AlutExit(); END.
using System; using System.Collections.Generic; namespace Morse { class Morse { static void Main(string[] args) { string word = "sos"; Dictionary<string, string> Codes = new Dictionary<string, string> { {"a", ".- "}, {"b", "-... "}, {"c", "-.-. "}, {"d", "-.. "}, {"e", ". "}, {"f", "..-. "}, {"g", "--. "}, {"h", ".... "}, {"i", ".. "}, {"j", ".--- "}, {"k", "-.- "}, {"l", ".-.. "}, {"m", "-- "}, {"n", "-. "}, {"o", "--- "}, {"p", ".--. "}, {"q", "--.- "}, {"r", ".-. "}, {"s", "... "}, {"t", "- "}, {"u", "..- "}, {"v", "...- "}, {"w", ".-- "}, {"x", "-..- "}, {"y", "-.-- "}, {"z", "--.. "}, {"0", "-----"}, {"1", ".----"}, {"2", "..---"}, {"3", "...--"}, {"4", "....-"}, {"5", "....."}, {"6", "-...."}, {"7", "--..."}, {"8", "---.."}, {"9", "----."} }; foreach (char c in word.ToCharArray()) { string rslt = Codes[c.ToString()].Trim(); foreach (char c2 in rslt.ToCharArray()) { if (c2 == '.') Console.Beep(1000, 250); else Console.Beep(1000, 750); } System.Threading.Thread.Sleep(50); } } } }
Write a version of this Pascal function in Java with identical behavior.
PROGRAM cw; USES OpenAL, HRTimer; CONST Morse: ARRAY [32..95] OF STRING = (' ','-.-.--','.-..-.','#','...-..-','%','.-...','.----.','-.--.','-.--.-','*','.-.-.','--..--','-....-','.-.-.-','-..-.','-----','.----','..---','...--','....-','.....','-....','--...','---..','----.','---...','-.-.-.','>','-...-','<','..--..','.--.-.','.-','-...','-.-.','-..','.','..-.','--.','....','..','.---','-.-','.-..','--','-.','---','.--.','--.-','.-.','...','-','..-','...-','.--','-..-','-.--','--..','-.--.','\','-.--.-','~','..--.-'); doh = 0.4; dit = 0.05; dah = 3 * dit + doh * dit; VAR buffer : TALuint; source : TALuint; sourcepos: ARRAY [0..2] OF TALfloat= ( 0.0, 0.0, 0.0 ); sourcevel: ARRAY [0..2] OF TALfloat= ( 0.0, 0.0, 0.0 ); argv: ARRAY OF PalByte; format: TALEnum; size: TALSizei; freq: TALSizei; loop: TALInt; data: TALVoid; rewind : BOOLEAN = FALSE; t : THRTimer; msg : STRING = 'the quick brown fox jumps over the lazy dog.'; PROCEDURE PlayS(s: Extended); BEGIN StartTimer(t); AlSourcePlay(source); WHILE readseconds(t) < s DO BEGIN END; IF rewind THEN AlSourceRewind(source); AlSourceStop(source); END; PROCEDURE Pause(s: Extended); BEGIN StartTimer(t); WHILE readseconds(t) < s DO BEGIN END; END; PROCEDURE doDit; BEGIN PlayS(dit); Pause(dit); END; PROCEDURE doDah; BEGIN PlayS(dah); Pause(dit); END; FUNCTION AtoM(ch: CHAR): STRING; VAR i: Integer; u: CHAR; BEGIN u := ch; IF ch IN ['a'..'z'] THEN u := chr(ord(ch) AND $5F); result := Morse[ord(u)]; FOR i := 1 TO Length(result) DO CASE result[i] OF '.': BEGIN doDit; Write('. ') END; '-': BEGIN doDah; Write('_ ') END; END; Pause(dah); Write(' '); IF u = ' ' THEN Write(' '); END; PROCEDURE StoM(s: STRING); VAR i: Integer; BEGIN FOR i := 1 TO Length(s) DO AtoM(s[i]); END; BEGIN InitOpenAL; AlutInit(nil,argv); AlGenBuffers(1, @buffer); AlutLoadWavFile('audiocheck.net_sin_500Hz_-3dBFS_1s.wav', format, data, size, freq, loop); AlBufferData(buffer, format, data, size, freq); AlutUnloadWav(format, data, size, freq); AlGenSources(1, @source); AlSourcei ( source, AL_BUFFER, buffer); AlSourcef ( source, AL_PITCH, 1.0 ); AlSourcef ( source, AL_GAIN, 1.0 ); AlSourcefv ( source, AL_POSITION, @sourcepos); AlSourcefv ( source, AL_VELOCITY, @sourcevel); AlSourcei ( source, AL_LOOPING, AL_TRUE); StoM(msg); Pause(1.0); AlSourceRewind(source); AlSourceStop(source); AlDeleteBuffers(1, @buffer); AlDeleteSources(1, @source); AlutExit(); END.
import java.util.*; public class MorseCode { final static String[][] code = { {"A", ".- "}, {"B", "-... "}, {"C", "-.-. "}, {"D", "-.. "}, {"E", ". "}, {"F", "..-. "}, {"G", "--. "}, {"H", ".... "}, {"I", ".. "}, {"J", ".--- "}, {"K", "-.- "}, {"L", ".-.. "}, {"M", "-- "}, {"N", "-. "}, {"O", "--- "}, {"P", ".--. "}, {"Q", "--.- "}, {"R", ".-. "}, {"S", "... "}, {"T", "- "}, {"U", "..- "}, {"V", "...- "}, {"W", ".- - "}, {"X", "-..- "}, {"Y", "-.-- "}, {"Z", "--.. "}, {"0", "----- "}, {"1", ".---- "}, {"2", "..--- "}, {"3", "...-- "}, {"4", "....- "}, {"5", "..... "}, {"6", "-.... "}, {"7", "--... "}, {"8", "---.. "}, {"9", "----. "}, {"'", ".----. "}, {":", "---... "}, {",", "--..-- "}, {"-", "-....- "}, {"(", "-.--.- "}, {".", ".-.-.- "}, {"?", "..--.. "}, {";", "-.-.-. "}, {"/", "-..-. "}, {"-", "..--.- "}, {")", "---.. "}, {"=", "-...- "}, {"@", ".--.-. "}, {"\"", ".-..-."}, {"+", ".-.-. "}, {" ", "/"}}; final static Map<Character, String> map = new HashMap<>(); static { for (String[] pair : code) map.put(pair[0].charAt(0), pair[1].trim()); } public static void main(String[] args) { printMorse("sos"); printMorse(" Hello World!"); printMorse("Rosetta Code"); } static void printMorse(String input) { System.out.printf("%s %n", input); input = input.trim().replaceAll("[ ]+", " ").toUpperCase(); for (char c : input.toCharArray()) { String s = map.get(c); if (s != null) System.out.printf("%s ", s); } System.out.println("\n"); } }
Convert this Pascal snippet to Python and keep its semantics consistent.
PROGRAM cw; USES OpenAL, HRTimer; CONST Morse: ARRAY [32..95] OF STRING = (' ','-.-.--','.-..-.','#','...-..-','%','.-...','.----.','-.--.','-.--.-','*','.-.-.','--..--','-....-','.-.-.-','-..-.','-----','.----','..---','...--','....-','.....','-....','--...','---..','----.','---...','-.-.-.','>','-...-','<','..--..','.--.-.','.-','-...','-.-.','-..','.','..-.','--.','....','..','.---','-.-','.-..','--','-.','---','.--.','--.-','.-.','...','-','..-','...-','.--','-..-','-.--','--..','-.--.','\','-.--.-','~','..--.-'); doh = 0.4; dit = 0.05; dah = 3 * dit + doh * dit; VAR buffer : TALuint; source : TALuint; sourcepos: ARRAY [0..2] OF TALfloat= ( 0.0, 0.0, 0.0 ); sourcevel: ARRAY [0..2] OF TALfloat= ( 0.0, 0.0, 0.0 ); argv: ARRAY OF PalByte; format: TALEnum; size: TALSizei; freq: TALSizei; loop: TALInt; data: TALVoid; rewind : BOOLEAN = FALSE; t : THRTimer; msg : STRING = 'the quick brown fox jumps over the lazy dog.'; PROCEDURE PlayS(s: Extended); BEGIN StartTimer(t); AlSourcePlay(source); WHILE readseconds(t) < s DO BEGIN END; IF rewind THEN AlSourceRewind(source); AlSourceStop(source); END; PROCEDURE Pause(s: Extended); BEGIN StartTimer(t); WHILE readseconds(t) < s DO BEGIN END; END; PROCEDURE doDit; BEGIN PlayS(dit); Pause(dit); END; PROCEDURE doDah; BEGIN PlayS(dah); Pause(dit); END; FUNCTION AtoM(ch: CHAR): STRING; VAR i: Integer; u: CHAR; BEGIN u := ch; IF ch IN ['a'..'z'] THEN u := chr(ord(ch) AND $5F); result := Morse[ord(u)]; FOR i := 1 TO Length(result) DO CASE result[i] OF '.': BEGIN doDit; Write('. ') END; '-': BEGIN doDah; Write('_ ') END; END; Pause(dah); Write(' '); IF u = ' ' THEN Write(' '); END; PROCEDURE StoM(s: STRING); VAR i: Integer; BEGIN FOR i := 1 TO Length(s) DO AtoM(s[i]); END; BEGIN InitOpenAL; AlutInit(nil,argv); AlGenBuffers(1, @buffer); AlutLoadWavFile('audiocheck.net_sin_500Hz_-3dBFS_1s.wav', format, data, size, freq, loop); AlBufferData(buffer, format, data, size, freq); AlutUnloadWav(format, data, size, freq); AlGenSources(1, @source); AlSourcei ( source, AL_BUFFER, buffer); AlSourcef ( source, AL_PITCH, 1.0 ); AlSourcef ( source, AL_GAIN, 1.0 ); AlSourcefv ( source, AL_POSITION, @sourcepos); AlSourcefv ( source, AL_VELOCITY, @sourcevel); AlSourcei ( source, AL_LOOPING, AL_TRUE); StoM(msg); Pause(1.0); AlSourceRewind(source); AlSourceStop(source); AlDeleteBuffers(1, @buffer); AlDeleteSources(1, @source); AlutExit(); END.
import time, winsound char2morse = { "!": "---.", "\"": ".-..-.", "$": "...-..-", "'": ".----.", "(": "-.--.", ")": "-.--.-", "+": ".-.-.", ",": "--..--", "-": "-....-", ".": ".-.-.-", "/": "-..-.", "0": "-----", "1": ".----", "2": "..---", "3": "...--", "4": "....-", "5": ".....", "6": "-....", "7": "--...", "8": "---..", "9": "----.", ":": "---...", ";": "-.-.-.", "=": "-...-", "?": "..--..", "@": ".--.-.", "A": ".-", "B": "-...", "C": "-.-.", "D": "-..", "E": ".", "F": "..-.", "G": "--.", "H": "....", "I": "..", "J": ".---", "K": "-.-", "L": ".-..", "M": "--", "N": "-.", "O": "---", "P": ".--.", "Q": "--.-", "R": ".-.", "S": "...", "T": "-", "U": "..-", "V": "...-", "W": ".--", "X": "-..-", "Y": "-.--", "Z": "--..", "[": "-.--.", "]": "-.--.-", "_": "..--.-", } e = 50 f = 1280 chargap = 1 wordgap = 7 def gap(n=1): time.sleep(n * e / 1000) off = gap def on(n=1): winsound.Beep(f, n * e) def dit(): on(); off() def dah(): on(3); off() def bloop(n=3): winsound.Beep(f//2, n * e) def windowsmorse(text): for word in text.strip().upper().split(): for char in word: for element in char2morse.get(char, '?'): if element == '-': dah() elif element == '.': dit() else: bloop() gap(chargap) gap(wordgap) while True: windowsmorse(input('A string to change into morse: '))
Transform the following Pascal implementation into VB, maintaining the same output and logic.
PROGRAM cw; USES OpenAL, HRTimer; CONST Morse: ARRAY [32..95] OF STRING = (' ','-.-.--','.-..-.','#','...-..-','%','.-...','.----.','-.--.','-.--.-','*','.-.-.','--..--','-....-','.-.-.-','-..-.','-----','.----','..---','...--','....-','.....','-....','--...','---..','----.','---...','-.-.-.','>','-...-','<','..--..','.--.-.','.-','-...','-.-.','-..','.','..-.','--.','....','..','.---','-.-','.-..','--','-.','---','.--.','--.-','.-.','...','-','..-','...-','.--','-..-','-.--','--..','-.--.','\','-.--.-','~','..--.-'); doh = 0.4; dit = 0.05; dah = 3 * dit + doh * dit; VAR buffer : TALuint; source : TALuint; sourcepos: ARRAY [0..2] OF TALfloat= ( 0.0, 0.0, 0.0 ); sourcevel: ARRAY [0..2] OF TALfloat= ( 0.0, 0.0, 0.0 ); argv: ARRAY OF PalByte; format: TALEnum; size: TALSizei; freq: TALSizei; loop: TALInt; data: TALVoid; rewind : BOOLEAN = FALSE; t : THRTimer; msg : STRING = 'the quick brown fox jumps over the lazy dog.'; PROCEDURE PlayS(s: Extended); BEGIN StartTimer(t); AlSourcePlay(source); WHILE readseconds(t) < s DO BEGIN END; IF rewind THEN AlSourceRewind(source); AlSourceStop(source); END; PROCEDURE Pause(s: Extended); BEGIN StartTimer(t); WHILE readseconds(t) < s DO BEGIN END; END; PROCEDURE doDit; BEGIN PlayS(dit); Pause(dit); END; PROCEDURE doDah; BEGIN PlayS(dah); Pause(dit); END; FUNCTION AtoM(ch: CHAR): STRING; VAR i: Integer; u: CHAR; BEGIN u := ch; IF ch IN ['a'..'z'] THEN u := chr(ord(ch) AND $5F); result := Morse[ord(u)]; FOR i := 1 TO Length(result) DO CASE result[i] OF '.': BEGIN doDit; Write('. ') END; '-': BEGIN doDah; Write('_ ') END; END; Pause(dah); Write(' '); IF u = ' ' THEN Write(' '); END; PROCEDURE StoM(s: STRING); VAR i: Integer; BEGIN FOR i := 1 TO Length(s) DO AtoM(s[i]); END; BEGIN InitOpenAL; AlutInit(nil,argv); AlGenBuffers(1, @buffer); AlutLoadWavFile('audiocheck.net_sin_500Hz_-3dBFS_1s.wav', format, data, size, freq, loop); AlBufferData(buffer, format, data, size, freq); AlutUnloadWav(format, data, size, freq); AlGenSources(1, @source); AlSourcei ( source, AL_BUFFER, buffer); AlSourcef ( source, AL_PITCH, 1.0 ); AlSourcef ( source, AL_GAIN, 1.0 ); AlSourcefv ( source, AL_POSITION, @sourcepos); AlSourcefv ( source, AL_VELOCITY, @sourcevel); AlSourcei ( source, AL_LOOPING, AL_TRUE); StoM(msg); Pause(1.0); AlSourceRewind(source); AlSourceStop(source); AlDeleteBuffers(1, @buffer); AlDeleteSources(1, @source); AlutExit(); END.
Option Explicit Private Declare Function Beep Lib "kernel32" (ByVal dwFreq As Long, ByVal dwDuration As Long) As Long Private Declare Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As Long) Private Const MORSE_ALPHA As String = ".-,-...,-.-.,-..,.,..-.,--.,....,..,.---,-.-,.-..,--,-.,---,.--.,--.-,.-.,...,-,..-,...-,.--,-..-,-.--,--.." Private Const MORSE_NUMERIC As String = "-----,.----,..---,...--,....-,.....,-....,--...,---..,----." Private Const ONE_UNIT As Integer = 100 Private Const BEEP_DOT As Integer = ONE_UNIT Private Const BEEP_DASH As Integer = 3 * ONE_UNIT Private Const BEEP_OTHER As Integer = 7 * ONE_UNIT Private Const DELAY As Integer = ONE_UNIT Private Const LETTERS_DELAY As Integer = 3 * ONE_UNIT Private Const SPACE_DELAY As Integer = 7 * ONE_UNIT Private Const FREQUENCY_CHARS As Integer = 1200 Private Const FREQUENCY_OTHERCHARS As Integer = 400 Sub Main() Dim p$, temp$ p = ToMorse("Hel/lo 123 world") temp = Replace(p, "+", "") Debug.Print Replace(temp, "_", "") PlayMorse p End Sub Private Function ToMorse(s As String) As String Dim i&, t$, j& s = UCase(s) For i = 1 To Len(s) j = Asc(Mid(s, i, 1)) Select Case j Case 65 To 90 t = t & Split(MORSE_ALPHA, ",")(j - 65) & "+" Case 48 To 57 t = t & Split(MORSE_NUMERIC, ",")(j - 48) & "+" Case 32 t = t & " " & "+" Case Else t = t & "_" & "+" End Select Next i ToMorse = t End Function Private Sub PlayMorse(s As String) Dim i& For i = 1 To Len(s) Select Case Mid(s, i, 1) Case ".": Beep FREQUENCY_CHARS, BEEP_DOT Case "-": Beep FREQUENCY_CHARS, BEEP_DASH Case "_": Beep FREQUENCY_OTHERCHARS, BEEP_OTHER Case "+": Sleep LETTERS_DELAY Case " ": Sleep SPACE_DELAY End Select Sleep DELAY Next i End Sub
Port the following code from Pascal to Go with equivalent syntax and logic.
PROGRAM cw; USES OpenAL, HRTimer; CONST Morse: ARRAY [32..95] OF STRING = (' ','-.-.--','.-..-.','#','...-..-','%','.-...','.----.','-.--.','-.--.-','*','.-.-.','--..--','-....-','.-.-.-','-..-.','-----','.----','..---','...--','....-','.....','-....','--...','---..','----.','---...','-.-.-.','>','-...-','<','..--..','.--.-.','.-','-...','-.-.','-..','.','..-.','--.','....','..','.---','-.-','.-..','--','-.','---','.--.','--.-','.-.','...','-','..-','...-','.--','-..-','-.--','--..','-.--.','\','-.--.-','~','..--.-'); doh = 0.4; dit = 0.05; dah = 3 * dit + doh * dit; VAR buffer : TALuint; source : TALuint; sourcepos: ARRAY [0..2] OF TALfloat= ( 0.0, 0.0, 0.0 ); sourcevel: ARRAY [0..2] OF TALfloat= ( 0.0, 0.0, 0.0 ); argv: ARRAY OF PalByte; format: TALEnum; size: TALSizei; freq: TALSizei; loop: TALInt; data: TALVoid; rewind : BOOLEAN = FALSE; t : THRTimer; msg : STRING = 'the quick brown fox jumps over the lazy dog.'; PROCEDURE PlayS(s: Extended); BEGIN StartTimer(t); AlSourcePlay(source); WHILE readseconds(t) < s DO BEGIN END; IF rewind THEN AlSourceRewind(source); AlSourceStop(source); END; PROCEDURE Pause(s: Extended); BEGIN StartTimer(t); WHILE readseconds(t) < s DO BEGIN END; END; PROCEDURE doDit; BEGIN PlayS(dit); Pause(dit); END; PROCEDURE doDah; BEGIN PlayS(dah); Pause(dit); END; FUNCTION AtoM(ch: CHAR): STRING; VAR i: Integer; u: CHAR; BEGIN u := ch; IF ch IN ['a'..'z'] THEN u := chr(ord(ch) AND $5F); result := Morse[ord(u)]; FOR i := 1 TO Length(result) DO CASE result[i] OF '.': BEGIN doDit; Write('. ') END; '-': BEGIN doDah; Write('_ ') END; END; Pause(dah); Write(' '); IF u = ' ' THEN Write(' '); END; PROCEDURE StoM(s: STRING); VAR i: Integer; BEGIN FOR i := 1 TO Length(s) DO AtoM(s[i]); END; BEGIN InitOpenAL; AlutInit(nil,argv); AlGenBuffers(1, @buffer); AlutLoadWavFile('audiocheck.net_sin_500Hz_-3dBFS_1s.wav', format, data, size, freq, loop); AlBufferData(buffer, format, data, size, freq); AlutUnloadWav(format, data, size, freq); AlGenSources(1, @source); AlSourcei ( source, AL_BUFFER, buffer); AlSourcef ( source, AL_PITCH, 1.0 ); AlSourcef ( source, AL_GAIN, 1.0 ); AlSourcefv ( source, AL_POSITION, @sourcepos); AlSourcefv ( source, AL_VELOCITY, @sourcevel); AlSourcei ( source, AL_LOOPING, AL_TRUE); StoM(msg); Pause(1.0); AlSourceRewind(source); AlSourceStop(source); AlDeleteBuffers(1, @buffer); AlDeleteSources(1, @source); AlutExit(); END.
package main import ( "flag" "fmt" "log" "regexp" "strings" "syscall" "time" "unicode" ) type key struct { duration int on bool sym string } var ( runeToKeys = map[rune][]key{} interCharGap = []key{{1, false, ""}} punctGap = []key{{7, false, " / "}} charGap = []key{{3, false, " "}} wordGap = []key{{7, false, " / "}} ) const rawMorse = ` A:.- J:.--- S:... 1:.---- .:.-.-.-  ::---... B:-... K:-.- T:- 2:..--- ,:--..--  ;:-.-.-. C:-.-. L:.-.. U:..- 3:...--  ?:..--.. =:-...- D:-.. M:-- V:...- 4:....- ':.----. +:.-.-. E:. N:-. W:.-- 5:.....  !:-.-.-- -:-....- F:..-. O:--- X:-..- 6:-.... /:-..-. _:..--.- G:--. P:.--. Y:-.-- 7:--... (:-.--. ":.-..-. H:.... Q:--.- Z:--.. 8:---.. ):-.--.- $:...-..- I:.. R:.-. 0:----- 9:----. &:.-... @:.--.-. ` func init() { r := regexp.MustCompile("([^ ]):([.-]+)") for _, m := range r.FindAllStringSubmatch(rawMorse, -1) { c := m[1][0] keys := []key{} for i, dd := range m[2] { if i > 0 { keys = append(keys, interCharGap...) } if dd == '.' { keys = append(keys, key{1, true, "."}) } else if dd == '-' { keys = append(keys, key{3, true, "-"}) } else { log.Fatalf("found %c in morse for %c", dd, c) } runeToKeys[rune(c)] = keys runeToKeys[unicode.ToLower(rune(c))] = keys } } } func MorseKeys(in string) ([]key, error) { afterWord := false afterChar := false result := []key{} for _, c := range in { if unicode.IsSpace(c) { afterWord = true continue } morse, ok := runeToKeys[c] if !ok { return nil, fmt.Errorf("can't translate %c to morse", c) } if unicode.IsPunct(c) && afterChar { result = append(result, punctGap...) } else if afterWord { result = append(result, wordGap...) } else if afterChar { result = append(result, charGap...) } result = append(result, morse...) afterChar = true afterWord = false } return result, nil } func main() { var ditDuration time.Duration flag.DurationVar(&ditDuration, "d", 40*time.Millisecond, "length of dit") flag.Parse() in := "hello world." if len(flag.Args()) > 1 { in = strings.Join(flag.Args(), " ") } keys, err := MorseKeys(in) if err != nil { log.Fatalf("failed to translate: %s", err) } for _, k := range keys { if k.on { if err := note(true); err != nil { log.Fatalf("failed to play note: %s", err) } } fmt.Print(k.sym) time.Sleep(ditDuration * time.Duration(k.duration)) if k.on { if err := note(false); err != nil { log.Fatalf("failed to stop note: %s", err) } } } fmt.Println() } var consoleFD uintptr func init() { fd, err := syscall.Open("/dev/console", syscall.O_WRONLY, 0) if err != nil { log.Fatalf("failed to get console device: %s", err) } consoleFD = uintptr(fd) } const KIOCSOUND = 0x4B2F const clockTickRate = 1193180 const freqHz = 600 func note(on bool) error { arg := uintptr(0) if on { arg = clockTickRate / freqHz } _, _, errno := syscall.Syscall(syscall.SYS_IOCTL, consoleFD, KIOCSOUND, arg) if errno != 0 { return errno } return nil }
Generate a C translation of this Perl snippet without changing its computational steps.
use Acme::AGMorse qw(SetMorseVals SendMorseMsg); SetMorseVals(20,30,400); SendMorseMsg('Hello World! abcdefg @\;'); exit;
#include <ctype.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #define BIND(A,L,H) ((L)<(A)?(A)<(H)?(A):(H):(L)) char dih[50],dah[50],medium[30],word[30], *dd[2] = {dih,dah}; const char *ascii = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789.,?'!/()&:;=+-_\"$@", *itu[] = { "13","3111","3131","311","1","1131","331","1111","11","1333","313","1311","33","31","333","1331","3313","131","111","3","113","1113","133","3113","3133","3311","33333","13333","11333","11133","11113","11111","31111","33111","33311","33331","131313","331133","113311","133331","313133","31131","31331","313313","13111","333111","313131","31113","13131","311113","113313","131131","1113113","133131" }; void append(char*s,const char*morse) { for (; *morse; ++morse) strcat(s,dd['3'==*morse]); strcat(s,medium); } char*translate(const char*i,char*o) { const char*pc; sprintf(o,"beep"); for (; *i; ++i) if (NULL == (pc = strchr(ascii,toupper(*i)))) strcat(o,word); else append(o,itu[pc-ascii]); strcat(o,word); return o; } int main(int ac,char*av[]) { char sin[73],sout[100000]; int dit = 100; if (1 < ac) { if (strlen(av[1]) != strspn(av[1],"0123456789")) return 0*fprintf(stderr,"use: %s [duration] dit in ms, default %d\n",*av,dit); dit = BIND(atoi(av[1]),1,1000); } sprintf(dah," -n -f 440 -l %d -D %d",3*dit,dit); sprintf(dih," -n -f 440 -l %d -D %d",dit,dit); sprintf(medium," -n -D %d",(3-1)*dit); sprintf(word," -n -D %d",(7-(3-1)-1)*dit); while (NULL != fgets(sin,72,stdin)) puts(translate(sin,sout)); return 0; }
Write the same code in C# as shown below in Perl.
use Acme::AGMorse qw(SetMorseVals SendMorseMsg); SetMorseVals(20,30,400); SendMorseMsg('Hello World! abcdefg @\;'); exit;
using System; using System.Collections.Generic; namespace Morse { class Morse { static void Main(string[] args) { string word = "sos"; Dictionary<string, string> Codes = new Dictionary<string, string> { {"a", ".- "}, {"b", "-... "}, {"c", "-.-. "}, {"d", "-.. "}, {"e", ". "}, {"f", "..-. "}, {"g", "--. "}, {"h", ".... "}, {"i", ".. "}, {"j", ".--- "}, {"k", "-.- "}, {"l", ".-.. "}, {"m", "-- "}, {"n", "-. "}, {"o", "--- "}, {"p", ".--. "}, {"q", "--.- "}, {"r", ".-. "}, {"s", "... "}, {"t", "- "}, {"u", "..- "}, {"v", "...- "}, {"w", ".-- "}, {"x", "-..- "}, {"y", "-.-- "}, {"z", "--.. "}, {"0", "-----"}, {"1", ".----"}, {"2", "..---"}, {"3", "...--"}, {"4", "....-"}, {"5", "....."}, {"6", "-...."}, {"7", "--..."}, {"8", "---.."}, {"9", "----."} }; foreach (char c in word.ToCharArray()) { string rslt = Codes[c.ToString()].Trim(); foreach (char c2 in rslt.ToCharArray()) { if (c2 == '.') Console.Beep(1000, 250); else Console.Beep(1000, 750); } System.Threading.Thread.Sleep(50); } } } }
Rewrite this program in Java while keeping its functionality equivalent to the Perl version.
use Acme::AGMorse qw(SetMorseVals SendMorseMsg); SetMorseVals(20,30,400); SendMorseMsg('Hello World! abcdefg @\;'); exit;
import java.util.*; public class MorseCode { final static String[][] code = { {"A", ".- "}, {"B", "-... "}, {"C", "-.-. "}, {"D", "-.. "}, {"E", ". "}, {"F", "..-. "}, {"G", "--. "}, {"H", ".... "}, {"I", ".. "}, {"J", ".--- "}, {"K", "-.- "}, {"L", ".-.. "}, {"M", "-- "}, {"N", "-. "}, {"O", "--- "}, {"P", ".--. "}, {"Q", "--.- "}, {"R", ".-. "}, {"S", "... "}, {"T", "- "}, {"U", "..- "}, {"V", "...- "}, {"W", ".- - "}, {"X", "-..- "}, {"Y", "-.-- "}, {"Z", "--.. "}, {"0", "----- "}, {"1", ".---- "}, {"2", "..--- "}, {"3", "...-- "}, {"4", "....- "}, {"5", "..... "}, {"6", "-.... "}, {"7", "--... "}, {"8", "---.. "}, {"9", "----. "}, {"'", ".----. "}, {":", "---... "}, {",", "--..-- "}, {"-", "-....- "}, {"(", "-.--.- "}, {".", ".-.-.- "}, {"?", "..--.. "}, {";", "-.-.-. "}, {"/", "-..-. "}, {"-", "..--.- "}, {")", "---.. "}, {"=", "-...- "}, {"@", ".--.-. "}, {"\"", ".-..-."}, {"+", ".-.-. "}, {" ", "/"}}; final static Map<Character, String> map = new HashMap<>(); static { for (String[] pair : code) map.put(pair[0].charAt(0), pair[1].trim()); } public static void main(String[] args) { printMorse("sos"); printMorse(" Hello World!"); printMorse("Rosetta Code"); } static void printMorse(String input) { System.out.printf("%s %n", input); input = input.trim().replaceAll("[ ]+", " ").toUpperCase(); for (char c : input.toCharArray()) { String s = map.get(c); if (s != null) System.out.printf("%s ", s); } System.out.println("\n"); } }
Write a version of this Perl function in Python with identical behavior.
use Acme::AGMorse qw(SetMorseVals SendMorseMsg); SetMorseVals(20,30,400); SendMorseMsg('Hello World! abcdefg @\;'); exit;
import time, winsound char2morse = { "!": "---.", "\"": ".-..-.", "$": "...-..-", "'": ".----.", "(": "-.--.", ")": "-.--.-", "+": ".-.-.", ",": "--..--", "-": "-....-", ".": ".-.-.-", "/": "-..-.", "0": "-----", "1": ".----", "2": "..---", "3": "...--", "4": "....-", "5": ".....", "6": "-....", "7": "--...", "8": "---..", "9": "----.", ":": "---...", ";": "-.-.-.", "=": "-...-", "?": "..--..", "@": ".--.-.", "A": ".-", "B": "-...", "C": "-.-.", "D": "-..", "E": ".", "F": "..-.", "G": "--.", "H": "....", "I": "..", "J": ".---", "K": "-.-", "L": ".-..", "M": "--", "N": "-.", "O": "---", "P": ".--.", "Q": "--.-", "R": ".-.", "S": "...", "T": "-", "U": "..-", "V": "...-", "W": ".--", "X": "-..-", "Y": "-.--", "Z": "--..", "[": "-.--.", "]": "-.--.-", "_": "..--.-", } e = 50 f = 1280 chargap = 1 wordgap = 7 def gap(n=1): time.sleep(n * e / 1000) off = gap def on(n=1): winsound.Beep(f, n * e) def dit(): on(); off() def dah(): on(3); off() def bloop(n=3): winsound.Beep(f//2, n * e) def windowsmorse(text): for word in text.strip().upper().split(): for char in word: for element in char2morse.get(char, '?'): if element == '-': dah() elif element == '.': dit() else: bloop() gap(chargap) gap(wordgap) while True: windowsmorse(input('A string to change into morse: '))
Translate this program into VB but keep the logic exactly as in Perl.
use Acme::AGMorse qw(SetMorseVals SendMorseMsg); SetMorseVals(20,30,400); SendMorseMsg('Hello World! abcdefg @\;'); exit;
Option Explicit Private Declare Function Beep Lib "kernel32" (ByVal dwFreq As Long, ByVal dwDuration As Long) As Long Private Declare Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As Long) Private Const MORSE_ALPHA As String = ".-,-...,-.-.,-..,.,..-.,--.,....,..,.---,-.-,.-..,--,-.,---,.--.,--.-,.-.,...,-,..-,...-,.--,-..-,-.--,--.." Private Const MORSE_NUMERIC As String = "-----,.----,..---,...--,....-,.....,-....,--...,---..,----." Private Const ONE_UNIT As Integer = 100 Private Const BEEP_DOT As Integer = ONE_UNIT Private Const BEEP_DASH As Integer = 3 * ONE_UNIT Private Const BEEP_OTHER As Integer = 7 * ONE_UNIT Private Const DELAY As Integer = ONE_UNIT Private Const LETTERS_DELAY As Integer = 3 * ONE_UNIT Private Const SPACE_DELAY As Integer = 7 * ONE_UNIT Private Const FREQUENCY_CHARS As Integer = 1200 Private Const FREQUENCY_OTHERCHARS As Integer = 400 Sub Main() Dim p$, temp$ p = ToMorse("Hel/lo 123 world") temp = Replace(p, "+", "") Debug.Print Replace(temp, "_", "") PlayMorse p End Sub Private Function ToMorse(s As String) As String Dim i&, t$, j& s = UCase(s) For i = 1 To Len(s) j = Asc(Mid(s, i, 1)) Select Case j Case 65 To 90 t = t & Split(MORSE_ALPHA, ",")(j - 65) & "+" Case 48 To 57 t = t & Split(MORSE_NUMERIC, ",")(j - 48) & "+" Case 32 t = t & " " & "+" Case Else t = t & "_" & "+" End Select Next i ToMorse = t End Function Private Sub PlayMorse(s As String) Dim i& For i = 1 To Len(s) Select Case Mid(s, i, 1) Case ".": Beep FREQUENCY_CHARS, BEEP_DOT Case "-": Beep FREQUENCY_CHARS, BEEP_DASH Case "_": Beep FREQUENCY_OTHERCHARS, BEEP_OTHER Case "+": Sleep LETTERS_DELAY Case " ": Sleep SPACE_DELAY End Select Sleep DELAY Next i End Sub
Write a version of this Perl function in Go with identical behavior.
use Acme::AGMorse qw(SetMorseVals SendMorseMsg); SetMorseVals(20,30,400); SendMorseMsg('Hello World! abcdefg @\;'); exit;
package main import ( "flag" "fmt" "log" "regexp" "strings" "syscall" "time" "unicode" ) type key struct { duration int on bool sym string } var ( runeToKeys = map[rune][]key{} interCharGap = []key{{1, false, ""}} punctGap = []key{{7, false, " / "}} charGap = []key{{3, false, " "}} wordGap = []key{{7, false, " / "}} ) const rawMorse = ` A:.- J:.--- S:... 1:.---- .:.-.-.-  ::---... B:-... K:-.- T:- 2:..--- ,:--..--  ;:-.-.-. C:-.-. L:.-.. U:..- 3:...--  ?:..--.. =:-...- D:-.. M:-- V:...- 4:....- ':.----. +:.-.-. E:. N:-. W:.-- 5:.....  !:-.-.-- -:-....- F:..-. O:--- X:-..- 6:-.... /:-..-. _:..--.- G:--. P:.--. Y:-.-- 7:--... (:-.--. ":.-..-. H:.... Q:--.- Z:--.. 8:---.. ):-.--.- $:...-..- I:.. R:.-. 0:----- 9:----. &:.-... @:.--.-. ` func init() { r := regexp.MustCompile("([^ ]):([.-]+)") for _, m := range r.FindAllStringSubmatch(rawMorse, -1) { c := m[1][0] keys := []key{} for i, dd := range m[2] { if i > 0 { keys = append(keys, interCharGap...) } if dd == '.' { keys = append(keys, key{1, true, "."}) } else if dd == '-' { keys = append(keys, key{3, true, "-"}) } else { log.Fatalf("found %c in morse for %c", dd, c) } runeToKeys[rune(c)] = keys runeToKeys[unicode.ToLower(rune(c))] = keys } } } func MorseKeys(in string) ([]key, error) { afterWord := false afterChar := false result := []key{} for _, c := range in { if unicode.IsSpace(c) { afterWord = true continue } morse, ok := runeToKeys[c] if !ok { return nil, fmt.Errorf("can't translate %c to morse", c) } if unicode.IsPunct(c) && afterChar { result = append(result, punctGap...) } else if afterWord { result = append(result, wordGap...) } else if afterChar { result = append(result, charGap...) } result = append(result, morse...) afterChar = true afterWord = false } return result, nil } func main() { var ditDuration time.Duration flag.DurationVar(&ditDuration, "d", 40*time.Millisecond, "length of dit") flag.Parse() in := "hello world." if len(flag.Args()) > 1 { in = strings.Join(flag.Args(), " ") } keys, err := MorseKeys(in) if err != nil { log.Fatalf("failed to translate: %s", err) } for _, k := range keys { if k.on { if err := note(true); err != nil { log.Fatalf("failed to play note: %s", err) } } fmt.Print(k.sym) time.Sleep(ditDuration * time.Duration(k.duration)) if k.on { if err := note(false); err != nil { log.Fatalf("failed to stop note: %s", err) } } } fmt.Println() } var consoleFD uintptr func init() { fd, err := syscall.Open("/dev/console", syscall.O_WRONLY, 0) if err != nil { log.Fatalf("failed to get console device: %s", err) } consoleFD = uintptr(fd) } const KIOCSOUND = 0x4B2F const clockTickRate = 1193180 const freqHz = 600 func note(on bool) error { arg := uintptr(0) if on { arg = clockTickRate / freqHz } _, _, errno := syscall.Syscall(syscall.SYS_IOCTL, consoleFD, KIOCSOUND, arg) if errno != 0 { return errno } return nil }
Produce a language-to-language conversion: from PowerShell to C, same semantics.
function Send-MorseCode { [CmdletBinding()] [OutputType([string])] Param ( [Parameter(Mandatory=$true, ValueFromPipeline=$true, Position=0)] [string] $Message, [switch] $ShowCode ) Begin { $morseCode = @{ a = ".-" ; b = "-..." ; c = "-.-." ; d = "-.." e = "." ; f = "..-." ; g = "--." ; h = "...." i = ".." ; j = ".---" ; k = "-.-" ; l = ".-.." m = "--" ; n = "-." ; o = "---" ; p = ".--." q = "--.-" ; r = ".-." ; s = "..." ; t = "-" u = "..-" ; v = "...-" ; w = ".--" ; x = "-..-" y = "-.--" ; z = "--.." ; 0 = "-----"; 1 = ".----" 2 = "..---"; 3 = "...--"; 4 = "....-"; 5 = "....." 6 = "-...."; 7 = "--..."; 8 = "---.."; 9 = "----." } } Process { foreach ($word in $Message) { $word.Split(" ",[StringSplitOptions]::RemoveEmptyEntries) | ForEach-Object { foreach ($char in $_.ToCharArray()) { if ($char -in $morseCode.Keys) { foreach ($code in ($morseCode."$char").ToCharArray()) { if ($code -eq ".") {$duration = 250} else {$duration = 750} [System.Console]::Beep(1000, $duration) Start-Sleep -Milliseconds 50 } if ($ShowCode) {Write-Host ("{0,-6}" -f ("{0,6}" -f $morseCode."$char")) -NoNewLine} } } if ($ShowCode) {Write-Host} } if ($ShowCode) {Write-Host} } } }
#include <ctype.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #define BIND(A,L,H) ((L)<(A)?(A)<(H)?(A):(H):(L)) char dih[50],dah[50],medium[30],word[30], *dd[2] = {dih,dah}; const char *ascii = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789.,?'!/()&:;=+-_\"$@", *itu[] = { "13","3111","3131","311","1","1131","331","1111","11","1333","313","1311","33","31","333","1331","3313","131","111","3","113","1113","133","3113","3133","3311","33333","13333","11333","11133","11113","11111","31111","33111","33311","33331","131313","331133","113311","133331","313133","31131","31331","313313","13111","333111","313131","31113","13131","311113","113313","131131","1113113","133131" }; void append(char*s,const char*morse) { for (; *morse; ++morse) strcat(s,dd['3'==*morse]); strcat(s,medium); } char*translate(const char*i,char*o) { const char*pc; sprintf(o,"beep"); for (; *i; ++i) if (NULL == (pc = strchr(ascii,toupper(*i)))) strcat(o,word); else append(o,itu[pc-ascii]); strcat(o,word); return o; } int main(int ac,char*av[]) { char sin[73],sout[100000]; int dit = 100; if (1 < ac) { if (strlen(av[1]) != strspn(av[1],"0123456789")) return 0*fprintf(stderr,"use: %s [duration] dit in ms, default %d\n",*av,dit); dit = BIND(atoi(av[1]),1,1000); } sprintf(dah," -n -f 440 -l %d -D %d",3*dit,dit); sprintf(dih," -n -f 440 -l %d -D %d",dit,dit); sprintf(medium," -n -D %d",(3-1)*dit); sprintf(word," -n -D %d",(7-(3-1)-1)*dit); while (NULL != fgets(sin,72,stdin)) puts(translate(sin,sout)); return 0; }
Write a version of this PowerShell function in C# with identical behavior.
function Send-MorseCode { [CmdletBinding()] [OutputType([string])] Param ( [Parameter(Mandatory=$true, ValueFromPipeline=$true, Position=0)] [string] $Message, [switch] $ShowCode ) Begin { $morseCode = @{ a = ".-" ; b = "-..." ; c = "-.-." ; d = "-.." e = "." ; f = "..-." ; g = "--." ; h = "...." i = ".." ; j = ".---" ; k = "-.-" ; l = ".-.." m = "--" ; n = "-." ; o = "---" ; p = ".--." q = "--.-" ; r = ".-." ; s = "..." ; t = "-" u = "..-" ; v = "...-" ; w = ".--" ; x = "-..-" y = "-.--" ; z = "--.." ; 0 = "-----"; 1 = ".----" 2 = "..---"; 3 = "...--"; 4 = "....-"; 5 = "....." 6 = "-...."; 7 = "--..."; 8 = "---.."; 9 = "----." } } Process { foreach ($word in $Message) { $word.Split(" ",[StringSplitOptions]::RemoveEmptyEntries) | ForEach-Object { foreach ($char in $_.ToCharArray()) { if ($char -in $morseCode.Keys) { foreach ($code in ($morseCode."$char").ToCharArray()) { if ($code -eq ".") {$duration = 250} else {$duration = 750} [System.Console]::Beep(1000, $duration) Start-Sleep -Milliseconds 50 } if ($ShowCode) {Write-Host ("{0,-6}" -f ("{0,6}" -f $morseCode."$char")) -NoNewLine} } } if ($ShowCode) {Write-Host} } if ($ShowCode) {Write-Host} } } }
using System; using System.Collections.Generic; namespace Morse { class Morse { static void Main(string[] args) { string word = "sos"; Dictionary<string, string> Codes = new Dictionary<string, string> { {"a", ".- "}, {"b", "-... "}, {"c", "-.-. "}, {"d", "-.. "}, {"e", ". "}, {"f", "..-. "}, {"g", "--. "}, {"h", ".... "}, {"i", ".. "}, {"j", ".--- "}, {"k", "-.- "}, {"l", ".-.. "}, {"m", "-- "}, {"n", "-. "}, {"o", "--- "}, {"p", ".--. "}, {"q", "--.- "}, {"r", ".-. "}, {"s", "... "}, {"t", "- "}, {"u", "..- "}, {"v", "...- "}, {"w", ".-- "}, {"x", "-..- "}, {"y", "-.-- "}, {"z", "--.. "}, {"0", "-----"}, {"1", ".----"}, {"2", "..---"}, {"3", "...--"}, {"4", "....-"}, {"5", "....."}, {"6", "-...."}, {"7", "--..."}, {"8", "---.."}, {"9", "----."} }; foreach (char c in word.ToCharArray()) { string rslt = Codes[c.ToString()].Trim(); foreach (char c2 in rslt.ToCharArray()) { if (c2 == '.') Console.Beep(1000, 250); else Console.Beep(1000, 750); } System.Threading.Thread.Sleep(50); } } } }
Translate the given PowerShell code snippet into Java without altering its behavior.
function Send-MorseCode { [CmdletBinding()] [OutputType([string])] Param ( [Parameter(Mandatory=$true, ValueFromPipeline=$true, Position=0)] [string] $Message, [switch] $ShowCode ) Begin { $morseCode = @{ a = ".-" ; b = "-..." ; c = "-.-." ; d = "-.." e = "." ; f = "..-." ; g = "--." ; h = "...." i = ".." ; j = ".---" ; k = "-.-" ; l = ".-.." m = "--" ; n = "-." ; o = "---" ; p = ".--." q = "--.-" ; r = ".-." ; s = "..." ; t = "-" u = "..-" ; v = "...-" ; w = ".--" ; x = "-..-" y = "-.--" ; z = "--.." ; 0 = "-----"; 1 = ".----" 2 = "..---"; 3 = "...--"; 4 = "....-"; 5 = "....." 6 = "-...."; 7 = "--..."; 8 = "---.."; 9 = "----." } } Process { foreach ($word in $Message) { $word.Split(" ",[StringSplitOptions]::RemoveEmptyEntries) | ForEach-Object { foreach ($char in $_.ToCharArray()) { if ($char -in $morseCode.Keys) { foreach ($code in ($morseCode."$char").ToCharArray()) { if ($code -eq ".") {$duration = 250} else {$duration = 750} [System.Console]::Beep(1000, $duration) Start-Sleep -Milliseconds 50 } if ($ShowCode) {Write-Host ("{0,-6}" -f ("{0,6}" -f $morseCode."$char")) -NoNewLine} } } if ($ShowCode) {Write-Host} } if ($ShowCode) {Write-Host} } } }
import java.util.*; public class MorseCode { final static String[][] code = { {"A", ".- "}, {"B", "-... "}, {"C", "-.-. "}, {"D", "-.. "}, {"E", ". "}, {"F", "..-. "}, {"G", "--. "}, {"H", ".... "}, {"I", ".. "}, {"J", ".--- "}, {"K", "-.- "}, {"L", ".-.. "}, {"M", "-- "}, {"N", "-. "}, {"O", "--- "}, {"P", ".--. "}, {"Q", "--.- "}, {"R", ".-. "}, {"S", "... "}, {"T", "- "}, {"U", "..- "}, {"V", "...- "}, {"W", ".- - "}, {"X", "-..- "}, {"Y", "-.-- "}, {"Z", "--.. "}, {"0", "----- "}, {"1", ".---- "}, {"2", "..--- "}, {"3", "...-- "}, {"4", "....- "}, {"5", "..... "}, {"6", "-.... "}, {"7", "--... "}, {"8", "---.. "}, {"9", "----. "}, {"'", ".----. "}, {":", "---... "}, {",", "--..-- "}, {"-", "-....- "}, {"(", "-.--.- "}, {".", ".-.-.- "}, {"?", "..--.. "}, {";", "-.-.-. "}, {"/", "-..-. "}, {"-", "..--.- "}, {")", "---.. "}, {"=", "-...- "}, {"@", ".--.-. "}, {"\"", ".-..-."}, {"+", ".-.-. "}, {" ", "/"}}; final static Map<Character, String> map = new HashMap<>(); static { for (String[] pair : code) map.put(pair[0].charAt(0), pair[1].trim()); } public static void main(String[] args) { printMorse("sos"); printMorse(" Hello World!"); printMorse("Rosetta Code"); } static void printMorse(String input) { System.out.printf("%s %n", input); input = input.trim().replaceAll("[ ]+", " ").toUpperCase(); for (char c : input.toCharArray()) { String s = map.get(c); if (s != null) System.out.printf("%s ", s); } System.out.println("\n"); } }
Can you help me rewrite this code in Python instead of PowerShell, keeping it the same logically?
function Send-MorseCode { [CmdletBinding()] [OutputType([string])] Param ( [Parameter(Mandatory=$true, ValueFromPipeline=$true, Position=0)] [string] $Message, [switch] $ShowCode ) Begin { $morseCode = @{ a = ".-" ; b = "-..." ; c = "-.-." ; d = "-.." e = "." ; f = "..-." ; g = "--." ; h = "...." i = ".." ; j = ".---" ; k = "-.-" ; l = ".-.." m = "--" ; n = "-." ; o = "---" ; p = ".--." q = "--.-" ; r = ".-." ; s = "..." ; t = "-" u = "..-" ; v = "...-" ; w = ".--" ; x = "-..-" y = "-.--" ; z = "--.." ; 0 = "-----"; 1 = ".----" 2 = "..---"; 3 = "...--"; 4 = "....-"; 5 = "....." 6 = "-...."; 7 = "--..."; 8 = "---.."; 9 = "----." } } Process { foreach ($word in $Message) { $word.Split(" ",[StringSplitOptions]::RemoveEmptyEntries) | ForEach-Object { foreach ($char in $_.ToCharArray()) { if ($char -in $morseCode.Keys) { foreach ($code in ($morseCode."$char").ToCharArray()) { if ($code -eq ".") {$duration = 250} else {$duration = 750} [System.Console]::Beep(1000, $duration) Start-Sleep -Milliseconds 50 } if ($ShowCode) {Write-Host ("{0,-6}" -f ("{0,6}" -f $morseCode."$char")) -NoNewLine} } } if ($ShowCode) {Write-Host} } if ($ShowCode) {Write-Host} } } }
import time, winsound char2morse = { "!": "---.", "\"": ".-..-.", "$": "...-..-", "'": ".----.", "(": "-.--.", ")": "-.--.-", "+": ".-.-.", ",": "--..--", "-": "-....-", ".": ".-.-.-", "/": "-..-.", "0": "-----", "1": ".----", "2": "..---", "3": "...--", "4": "....-", "5": ".....", "6": "-....", "7": "--...", "8": "---..", "9": "----.", ":": "---...", ";": "-.-.-.", "=": "-...-", "?": "..--..", "@": ".--.-.", "A": ".-", "B": "-...", "C": "-.-.", "D": "-..", "E": ".", "F": "..-.", "G": "--.", "H": "....", "I": "..", "J": ".---", "K": "-.-", "L": ".-..", "M": "--", "N": "-.", "O": "---", "P": ".--.", "Q": "--.-", "R": ".-.", "S": "...", "T": "-", "U": "..-", "V": "...-", "W": ".--", "X": "-..-", "Y": "-.--", "Z": "--..", "[": "-.--.", "]": "-.--.-", "_": "..--.-", } e = 50 f = 1280 chargap = 1 wordgap = 7 def gap(n=1): time.sleep(n * e / 1000) off = gap def on(n=1): winsound.Beep(f, n * e) def dit(): on(); off() def dah(): on(3); off() def bloop(n=3): winsound.Beep(f//2, n * e) def windowsmorse(text): for word in text.strip().upper().split(): for char in word: for element in char2morse.get(char, '?'): if element == '-': dah() elif element == '.': dit() else: bloop() gap(chargap) gap(wordgap) while True: windowsmorse(input('A string to change into morse: '))
Translate the given PowerShell code snippet into VB without altering its behavior.
function Send-MorseCode { [CmdletBinding()] [OutputType([string])] Param ( [Parameter(Mandatory=$true, ValueFromPipeline=$true, Position=0)] [string] $Message, [switch] $ShowCode ) Begin { $morseCode = @{ a = ".-" ; b = "-..." ; c = "-.-." ; d = "-.." e = "." ; f = "..-." ; g = "--." ; h = "...." i = ".." ; j = ".---" ; k = "-.-" ; l = ".-.." m = "--" ; n = "-." ; o = "---" ; p = ".--." q = "--.-" ; r = ".-." ; s = "..." ; t = "-" u = "..-" ; v = "...-" ; w = ".--" ; x = "-..-" y = "-.--" ; z = "--.." ; 0 = "-----"; 1 = ".----" 2 = "..---"; 3 = "...--"; 4 = "....-"; 5 = "....." 6 = "-...."; 7 = "--..."; 8 = "---.."; 9 = "----." } } Process { foreach ($word in $Message) { $word.Split(" ",[StringSplitOptions]::RemoveEmptyEntries) | ForEach-Object { foreach ($char in $_.ToCharArray()) { if ($char -in $morseCode.Keys) { foreach ($code in ($morseCode."$char").ToCharArray()) { if ($code -eq ".") {$duration = 250} else {$duration = 750} [System.Console]::Beep(1000, $duration) Start-Sleep -Milliseconds 50 } if ($ShowCode) {Write-Host ("{0,-6}" -f ("{0,6}" -f $morseCode."$char")) -NoNewLine} } } if ($ShowCode) {Write-Host} } if ($ShowCode) {Write-Host} } } }
Option Explicit Private Declare Function Beep Lib "kernel32" (ByVal dwFreq As Long, ByVal dwDuration As Long) As Long Private Declare Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As Long) Private Const MORSE_ALPHA As String = ".-,-...,-.-.,-..,.,..-.,--.,....,..,.---,-.-,.-..,--,-.,---,.--.,--.-,.-.,...,-,..-,...-,.--,-..-,-.--,--.." Private Const MORSE_NUMERIC As String = "-----,.----,..---,...--,....-,.....,-....,--...,---..,----." Private Const ONE_UNIT As Integer = 100 Private Const BEEP_DOT As Integer = ONE_UNIT Private Const BEEP_DASH As Integer = 3 * ONE_UNIT Private Const BEEP_OTHER As Integer = 7 * ONE_UNIT Private Const DELAY As Integer = ONE_UNIT Private Const LETTERS_DELAY As Integer = 3 * ONE_UNIT Private Const SPACE_DELAY As Integer = 7 * ONE_UNIT Private Const FREQUENCY_CHARS As Integer = 1200 Private Const FREQUENCY_OTHERCHARS As Integer = 400 Sub Main() Dim p$, temp$ p = ToMorse("Hel/lo 123 world") temp = Replace(p, "+", "") Debug.Print Replace(temp, "_", "") PlayMorse p End Sub Private Function ToMorse(s As String) As String Dim i&, t$, j& s = UCase(s) For i = 1 To Len(s) j = Asc(Mid(s, i, 1)) Select Case j Case 65 To 90 t = t & Split(MORSE_ALPHA, ",")(j - 65) & "+" Case 48 To 57 t = t & Split(MORSE_NUMERIC, ",")(j - 48) & "+" Case 32 t = t & " " & "+" Case Else t = t & "_" & "+" End Select Next i ToMorse = t End Function Private Sub PlayMorse(s As String) Dim i& For i = 1 To Len(s) Select Case Mid(s, i, 1) Case ".": Beep FREQUENCY_CHARS, BEEP_DOT Case "-": Beep FREQUENCY_CHARS, BEEP_DASH Case "_": Beep FREQUENCY_OTHERCHARS, BEEP_OTHER Case "+": Sleep LETTERS_DELAY Case " ": Sleep SPACE_DELAY End Select Sleep DELAY Next i End Sub
Transform the following PowerShell implementation into Go, maintaining the same output and logic.
function Send-MorseCode { [CmdletBinding()] [OutputType([string])] Param ( [Parameter(Mandatory=$true, ValueFromPipeline=$true, Position=0)] [string] $Message, [switch] $ShowCode ) Begin { $morseCode = @{ a = ".-" ; b = "-..." ; c = "-.-." ; d = "-.." e = "." ; f = "..-." ; g = "--." ; h = "...." i = ".." ; j = ".---" ; k = "-.-" ; l = ".-.." m = "--" ; n = "-." ; o = "---" ; p = ".--." q = "--.-" ; r = ".-." ; s = "..." ; t = "-" u = "..-" ; v = "...-" ; w = ".--" ; x = "-..-" y = "-.--" ; z = "--.." ; 0 = "-----"; 1 = ".----" 2 = "..---"; 3 = "...--"; 4 = "....-"; 5 = "....." 6 = "-...."; 7 = "--..."; 8 = "---.."; 9 = "----." } } Process { foreach ($word in $Message) { $word.Split(" ",[StringSplitOptions]::RemoveEmptyEntries) | ForEach-Object { foreach ($char in $_.ToCharArray()) { if ($char -in $morseCode.Keys) { foreach ($code in ($morseCode."$char").ToCharArray()) { if ($code -eq ".") {$duration = 250} else {$duration = 750} [System.Console]::Beep(1000, $duration) Start-Sleep -Milliseconds 50 } if ($ShowCode) {Write-Host ("{0,-6}" -f ("{0,6}" -f $morseCode."$char")) -NoNewLine} } } if ($ShowCode) {Write-Host} } if ($ShowCode) {Write-Host} } } }
package main import ( "flag" "fmt" "log" "regexp" "strings" "syscall" "time" "unicode" ) type key struct { duration int on bool sym string } var ( runeToKeys = map[rune][]key{} interCharGap = []key{{1, false, ""}} punctGap = []key{{7, false, " / "}} charGap = []key{{3, false, " "}} wordGap = []key{{7, false, " / "}} ) const rawMorse = ` A:.- J:.--- S:... 1:.---- .:.-.-.-  ::---... B:-... K:-.- T:- 2:..--- ,:--..--  ;:-.-.-. C:-.-. L:.-.. U:..- 3:...--  ?:..--.. =:-...- D:-.. M:-- V:...- 4:....- ':.----. +:.-.-. E:. N:-. W:.-- 5:.....  !:-.-.-- -:-....- F:..-. O:--- X:-..- 6:-.... /:-..-. _:..--.- G:--. P:.--. Y:-.-- 7:--... (:-.--. ":.-..-. H:.... Q:--.- Z:--.. 8:---.. ):-.--.- $:...-..- I:.. R:.-. 0:----- 9:----. &:.-... @:.--.-. ` func init() { r := regexp.MustCompile("([^ ]):([.-]+)") for _, m := range r.FindAllStringSubmatch(rawMorse, -1) { c := m[1][0] keys := []key{} for i, dd := range m[2] { if i > 0 { keys = append(keys, interCharGap...) } if dd == '.' { keys = append(keys, key{1, true, "."}) } else if dd == '-' { keys = append(keys, key{3, true, "-"}) } else { log.Fatalf("found %c in morse for %c", dd, c) } runeToKeys[rune(c)] = keys runeToKeys[unicode.ToLower(rune(c))] = keys } } } func MorseKeys(in string) ([]key, error) { afterWord := false afterChar := false result := []key{} for _, c := range in { if unicode.IsSpace(c) { afterWord = true continue } morse, ok := runeToKeys[c] if !ok { return nil, fmt.Errorf("can't translate %c to morse", c) } if unicode.IsPunct(c) && afterChar { result = append(result, punctGap...) } else if afterWord { result = append(result, wordGap...) } else if afterChar { result = append(result, charGap...) } result = append(result, morse...) afterChar = true afterWord = false } return result, nil } func main() { var ditDuration time.Duration flag.DurationVar(&ditDuration, "d", 40*time.Millisecond, "length of dit") flag.Parse() in := "hello world." if len(flag.Args()) > 1 { in = strings.Join(flag.Args(), " ") } keys, err := MorseKeys(in) if err != nil { log.Fatalf("failed to translate: %s", err) } for _, k := range keys { if k.on { if err := note(true); err != nil { log.Fatalf("failed to play note: %s", err) } } fmt.Print(k.sym) time.Sleep(ditDuration * time.Duration(k.duration)) if k.on { if err := note(false); err != nil { log.Fatalf("failed to stop note: %s", err) } } } fmt.Println() } var consoleFD uintptr func init() { fd, err := syscall.Open("/dev/console", syscall.O_WRONLY, 0) if err != nil { log.Fatalf("failed to get console device: %s", err) } consoleFD = uintptr(fd) } const KIOCSOUND = 0x4B2F const clockTickRate = 1193180 const freqHz = 600 func note(on bool) error { arg := uintptr(0) if on { arg = clockTickRate / freqHz } _, _, errno := syscall.Syscall(syscall.SYS_IOCTL, consoleFD, KIOCSOUND, arg) if errno != 0 { return errno } return nil }
Translate this program into C but keep the logic exactly as in Racket.
#lang racket (require ffi/unsafe ffi/unsafe/define) (define-ffi-definer defmm (ffi-lib "Winmm")) (defmm midiOutOpen (_fun [h : (_ptr o _int32)] [_int = -1] [_pointer = #f] [_pointer = #f] [_int32 = 0] -> _void -> h)) (defmm midiOutShortMsg (_fun _int32 _int32 -> _void)) (define M (midiOutOpen)) (define (midi x y z) (midiOutShortMsg M (+ x (* 256 y) (* 65536 z)))) (define raw-codes '("a.-|b-...|c-.-.|d-..|e.|f..-.|g--.|h....|i..|j.---|k-.-|l.-..|m--|n-." "|o---|p--.-|q--.-|r.-.|s...|t-|u..-|v...-|w.--|x-..-|y-.--|z--..|1.----" "|2..---|3...--|4....-|5.....|6-....|7--...|8---..|9----.|0-----")) (define codes (for/list ([x (regexp-split #rx"\\|" (string-append* raw-codes))]) (cons (string-ref x 0) (substring x 1)))) (define (morse str [unit 0.1]) (define (sound len) (midi #x90 72 127) (sleep (* len unit)) (midi #x90 72 0) (sleep unit)) (define (play str) (midi #xC0 #x35 0) (for ([c str]) (case c [(#\.) (sound 1)] [(#\-) (sound 3)] [(#\ ) (sleep (* 3 unit))]))) (let* ([str (string-foldcase str)] [str (regexp-replace* #rx"[,: [str (regexp-replace* #rx"[.!?]+" str ".")] [str (string-normalize-spaces str)]) (for ([s (string-split str)]) (define m (string-join (for/list ([c s]) (cond [(assq c codes) => cdr] [else (case c [(#\space) " "] [(#\.) " "] [else ""])])))) (printf "~a: ~a\n" s m) (play (string-append m " "))))) (morse "Say something here")
#include <ctype.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #define BIND(A,L,H) ((L)<(A)?(A)<(H)?(A):(H):(L)) char dih[50],dah[50],medium[30],word[30], *dd[2] = {dih,dah}; const char *ascii = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789.,?'!/()&:;=+-_\"$@", *itu[] = { "13","3111","3131","311","1","1131","331","1111","11","1333","313","1311","33","31","333","1331","3313","131","111","3","113","1113","133","3113","3133","3311","33333","13333","11333","11133","11113","11111","31111","33111","33311","33331","131313","331133","113311","133331","313133","31131","31331","313313","13111","333111","313131","31113","13131","311113","113313","131131","1113113","133131" }; void append(char*s,const char*morse) { for (; *morse; ++morse) strcat(s,dd['3'==*morse]); strcat(s,medium); } char*translate(const char*i,char*o) { const char*pc; sprintf(o,"beep"); for (; *i; ++i) if (NULL == (pc = strchr(ascii,toupper(*i)))) strcat(o,word); else append(o,itu[pc-ascii]); strcat(o,word); return o; } int main(int ac,char*av[]) { char sin[73],sout[100000]; int dit = 100; if (1 < ac) { if (strlen(av[1]) != strspn(av[1],"0123456789")) return 0*fprintf(stderr,"use: %s [duration] dit in ms, default %d\n",*av,dit); dit = BIND(atoi(av[1]),1,1000); } sprintf(dah," -n -f 440 -l %d -D %d",3*dit,dit); sprintf(dih," -n -f 440 -l %d -D %d",dit,dit); sprintf(medium," -n -D %d",(3-1)*dit); sprintf(word," -n -D %d",(7-(3-1)-1)*dit); while (NULL != fgets(sin,72,stdin)) puts(translate(sin,sout)); return 0; }
Convert this Racket block to C#, preserving its control flow and logic.
#lang racket (require ffi/unsafe ffi/unsafe/define) (define-ffi-definer defmm (ffi-lib "Winmm")) (defmm midiOutOpen (_fun [h : (_ptr o _int32)] [_int = -1] [_pointer = #f] [_pointer = #f] [_int32 = 0] -> _void -> h)) (defmm midiOutShortMsg (_fun _int32 _int32 -> _void)) (define M (midiOutOpen)) (define (midi x y z) (midiOutShortMsg M (+ x (* 256 y) (* 65536 z)))) (define raw-codes '("a.-|b-...|c-.-.|d-..|e.|f..-.|g--.|h....|i..|j.---|k-.-|l.-..|m--|n-." "|o---|p--.-|q--.-|r.-.|s...|t-|u..-|v...-|w.--|x-..-|y-.--|z--..|1.----" "|2..---|3...--|4....-|5.....|6-....|7--...|8---..|9----.|0-----")) (define codes (for/list ([x (regexp-split #rx"\\|" (string-append* raw-codes))]) (cons (string-ref x 0) (substring x 1)))) (define (morse str [unit 0.1]) (define (sound len) (midi #x90 72 127) (sleep (* len unit)) (midi #x90 72 0) (sleep unit)) (define (play str) (midi #xC0 #x35 0) (for ([c str]) (case c [(#\.) (sound 1)] [(#\-) (sound 3)] [(#\ ) (sleep (* 3 unit))]))) (let* ([str (string-foldcase str)] [str (regexp-replace* #rx"[,: [str (regexp-replace* #rx"[.!?]+" str ".")] [str (string-normalize-spaces str)]) (for ([s (string-split str)]) (define m (string-join (for/list ([c s]) (cond [(assq c codes) => cdr] [else (case c [(#\space) " "] [(#\.) " "] [else ""])])))) (printf "~a: ~a\n" s m) (play (string-append m " "))))) (morse "Say something here")
using System; using System.Collections.Generic; namespace Morse { class Morse { static void Main(string[] args) { string word = "sos"; Dictionary<string, string> Codes = new Dictionary<string, string> { {"a", ".- "}, {"b", "-... "}, {"c", "-.-. "}, {"d", "-.. "}, {"e", ". "}, {"f", "..-. "}, {"g", "--. "}, {"h", ".... "}, {"i", ".. "}, {"j", ".--- "}, {"k", "-.- "}, {"l", ".-.. "}, {"m", "-- "}, {"n", "-. "}, {"o", "--- "}, {"p", ".--. "}, {"q", "--.- "}, {"r", ".-. "}, {"s", "... "}, {"t", "- "}, {"u", "..- "}, {"v", "...- "}, {"w", ".-- "}, {"x", "-..- "}, {"y", "-.-- "}, {"z", "--.. "}, {"0", "-----"}, {"1", ".----"}, {"2", "..---"}, {"3", "...--"}, {"4", "....-"}, {"5", "....."}, {"6", "-...."}, {"7", "--..."}, {"8", "---.."}, {"9", "----."} }; foreach (char c in word.ToCharArray()) { string rslt = Codes[c.ToString()].Trim(); foreach (char c2 in rslt.ToCharArray()) { if (c2 == '.') Console.Beep(1000, 250); else Console.Beep(1000, 750); } System.Threading.Thread.Sleep(50); } } } }
Produce a language-to-language conversion: from Racket to Java, same semantics.
#lang racket (require ffi/unsafe ffi/unsafe/define) (define-ffi-definer defmm (ffi-lib "Winmm")) (defmm midiOutOpen (_fun [h : (_ptr o _int32)] [_int = -1] [_pointer = #f] [_pointer = #f] [_int32 = 0] -> _void -> h)) (defmm midiOutShortMsg (_fun _int32 _int32 -> _void)) (define M (midiOutOpen)) (define (midi x y z) (midiOutShortMsg M (+ x (* 256 y) (* 65536 z)))) (define raw-codes '("a.-|b-...|c-.-.|d-..|e.|f..-.|g--.|h....|i..|j.---|k-.-|l.-..|m--|n-." "|o---|p--.-|q--.-|r.-.|s...|t-|u..-|v...-|w.--|x-..-|y-.--|z--..|1.----" "|2..---|3...--|4....-|5.....|6-....|7--...|8---..|9----.|0-----")) (define codes (for/list ([x (regexp-split #rx"\\|" (string-append* raw-codes))]) (cons (string-ref x 0) (substring x 1)))) (define (morse str [unit 0.1]) (define (sound len) (midi #x90 72 127) (sleep (* len unit)) (midi #x90 72 0) (sleep unit)) (define (play str) (midi #xC0 #x35 0) (for ([c str]) (case c [(#\.) (sound 1)] [(#\-) (sound 3)] [(#\ ) (sleep (* 3 unit))]))) (let* ([str (string-foldcase str)] [str (regexp-replace* #rx"[,: [str (regexp-replace* #rx"[.!?]+" str ".")] [str (string-normalize-spaces str)]) (for ([s (string-split str)]) (define m (string-join (for/list ([c s]) (cond [(assq c codes) => cdr] [else (case c [(#\space) " "] [(#\.) " "] [else ""])])))) (printf "~a: ~a\n" s m) (play (string-append m " "))))) (morse "Say something here")
import java.util.*; public class MorseCode { final static String[][] code = { {"A", ".- "}, {"B", "-... "}, {"C", "-.-. "}, {"D", "-.. "}, {"E", ". "}, {"F", "..-. "}, {"G", "--. "}, {"H", ".... "}, {"I", ".. "}, {"J", ".--- "}, {"K", "-.- "}, {"L", ".-.. "}, {"M", "-- "}, {"N", "-. "}, {"O", "--- "}, {"P", ".--. "}, {"Q", "--.- "}, {"R", ".-. "}, {"S", "... "}, {"T", "- "}, {"U", "..- "}, {"V", "...- "}, {"W", ".- - "}, {"X", "-..- "}, {"Y", "-.-- "}, {"Z", "--.. "}, {"0", "----- "}, {"1", ".---- "}, {"2", "..--- "}, {"3", "...-- "}, {"4", "....- "}, {"5", "..... "}, {"6", "-.... "}, {"7", "--... "}, {"8", "---.. "}, {"9", "----. "}, {"'", ".----. "}, {":", "---... "}, {",", "--..-- "}, {"-", "-....- "}, {"(", "-.--.- "}, {".", ".-.-.- "}, {"?", "..--.. "}, {";", "-.-.-. "}, {"/", "-..-. "}, {"-", "..--.- "}, {")", "---.. "}, {"=", "-...- "}, {"@", ".--.-. "}, {"\"", ".-..-."}, {"+", ".-.-. "}, {" ", "/"}}; final static Map<Character, String> map = new HashMap<>(); static { for (String[] pair : code) map.put(pair[0].charAt(0), pair[1].trim()); } public static void main(String[] args) { printMorse("sos"); printMorse(" Hello World!"); printMorse("Rosetta Code"); } static void printMorse(String input) { System.out.printf("%s %n", input); input = input.trim().replaceAll("[ ]+", " ").toUpperCase(); for (char c : input.toCharArray()) { String s = map.get(c); if (s != null) System.out.printf("%s ", s); } System.out.println("\n"); } }
Translate the given Racket code snippet into Python without altering its behavior.
#lang racket (require ffi/unsafe ffi/unsafe/define) (define-ffi-definer defmm (ffi-lib "Winmm")) (defmm midiOutOpen (_fun [h : (_ptr o _int32)] [_int = -1] [_pointer = #f] [_pointer = #f] [_int32 = 0] -> _void -> h)) (defmm midiOutShortMsg (_fun _int32 _int32 -> _void)) (define M (midiOutOpen)) (define (midi x y z) (midiOutShortMsg M (+ x (* 256 y) (* 65536 z)))) (define raw-codes '("a.-|b-...|c-.-.|d-..|e.|f..-.|g--.|h....|i..|j.---|k-.-|l.-..|m--|n-." "|o---|p--.-|q--.-|r.-.|s...|t-|u..-|v...-|w.--|x-..-|y-.--|z--..|1.----" "|2..---|3...--|4....-|5.....|6-....|7--...|8---..|9----.|0-----")) (define codes (for/list ([x (regexp-split #rx"\\|" (string-append* raw-codes))]) (cons (string-ref x 0) (substring x 1)))) (define (morse str [unit 0.1]) (define (sound len) (midi #x90 72 127) (sleep (* len unit)) (midi #x90 72 0) (sleep unit)) (define (play str) (midi #xC0 #x35 0) (for ([c str]) (case c [(#\.) (sound 1)] [(#\-) (sound 3)] [(#\ ) (sleep (* 3 unit))]))) (let* ([str (string-foldcase str)] [str (regexp-replace* #rx"[,: [str (regexp-replace* #rx"[.!?]+" str ".")] [str (string-normalize-spaces str)]) (for ([s (string-split str)]) (define m (string-join (for/list ([c s]) (cond [(assq c codes) => cdr] [else (case c [(#\space) " "] [(#\.) " "] [else ""])])))) (printf "~a: ~a\n" s m) (play (string-append m " "))))) (morse "Say something here")
import time, winsound char2morse = { "!": "---.", "\"": ".-..-.", "$": "...-..-", "'": ".----.", "(": "-.--.", ")": "-.--.-", "+": ".-.-.", ",": "--..--", "-": "-....-", ".": ".-.-.-", "/": "-..-.", "0": "-----", "1": ".----", "2": "..---", "3": "...--", "4": "....-", "5": ".....", "6": "-....", "7": "--...", "8": "---..", "9": "----.", ":": "---...", ";": "-.-.-.", "=": "-...-", "?": "..--..", "@": ".--.-.", "A": ".-", "B": "-...", "C": "-.-.", "D": "-..", "E": ".", "F": "..-.", "G": "--.", "H": "....", "I": "..", "J": ".---", "K": "-.-", "L": ".-..", "M": "--", "N": "-.", "O": "---", "P": ".--.", "Q": "--.-", "R": ".-.", "S": "...", "T": "-", "U": "..-", "V": "...-", "W": ".--", "X": "-..-", "Y": "-.--", "Z": "--..", "[": "-.--.", "]": "-.--.-", "_": "..--.-", } e = 50 f = 1280 chargap = 1 wordgap = 7 def gap(n=1): time.sleep(n * e / 1000) off = gap def on(n=1): winsound.Beep(f, n * e) def dit(): on(); off() def dah(): on(3); off() def bloop(n=3): winsound.Beep(f//2, n * e) def windowsmorse(text): for word in text.strip().upper().split(): for char in word: for element in char2morse.get(char, '?'): if element == '-': dah() elif element == '.': dit() else: bloop() gap(chargap) gap(wordgap) while True: windowsmorse(input('A string to change into morse: '))
Ensure the translated VB code behaves exactly like the original Racket snippet.
#lang racket (require ffi/unsafe ffi/unsafe/define) (define-ffi-definer defmm (ffi-lib "Winmm")) (defmm midiOutOpen (_fun [h : (_ptr o _int32)] [_int = -1] [_pointer = #f] [_pointer = #f] [_int32 = 0] -> _void -> h)) (defmm midiOutShortMsg (_fun _int32 _int32 -> _void)) (define M (midiOutOpen)) (define (midi x y z) (midiOutShortMsg M (+ x (* 256 y) (* 65536 z)))) (define raw-codes '("a.-|b-...|c-.-.|d-..|e.|f..-.|g--.|h....|i..|j.---|k-.-|l.-..|m--|n-." "|o---|p--.-|q--.-|r.-.|s...|t-|u..-|v...-|w.--|x-..-|y-.--|z--..|1.----" "|2..---|3...--|4....-|5.....|6-....|7--...|8---..|9----.|0-----")) (define codes (for/list ([x (regexp-split #rx"\\|" (string-append* raw-codes))]) (cons (string-ref x 0) (substring x 1)))) (define (morse str [unit 0.1]) (define (sound len) (midi #x90 72 127) (sleep (* len unit)) (midi #x90 72 0) (sleep unit)) (define (play str) (midi #xC0 #x35 0) (for ([c str]) (case c [(#\.) (sound 1)] [(#\-) (sound 3)] [(#\ ) (sleep (* 3 unit))]))) (let* ([str (string-foldcase str)] [str (regexp-replace* #rx"[,: [str (regexp-replace* #rx"[.!?]+" str ".")] [str (string-normalize-spaces str)]) (for ([s (string-split str)]) (define m (string-join (for/list ([c s]) (cond [(assq c codes) => cdr] [else (case c [(#\space) " "] [(#\.) " "] [else ""])])))) (printf "~a: ~a\n" s m) (play (string-append m " "))))) (morse "Say something here")
Option Explicit Private Declare Function Beep Lib "kernel32" (ByVal dwFreq As Long, ByVal dwDuration As Long) As Long Private Declare Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As Long) Private Const MORSE_ALPHA As String = ".-,-...,-.-.,-..,.,..-.,--.,....,..,.---,-.-,.-..,--,-.,---,.--.,--.-,.-.,...,-,..-,...-,.--,-..-,-.--,--.." Private Const MORSE_NUMERIC As String = "-----,.----,..---,...--,....-,.....,-....,--...,---..,----." Private Const ONE_UNIT As Integer = 100 Private Const BEEP_DOT As Integer = ONE_UNIT Private Const BEEP_DASH As Integer = 3 * ONE_UNIT Private Const BEEP_OTHER As Integer = 7 * ONE_UNIT Private Const DELAY As Integer = ONE_UNIT Private Const LETTERS_DELAY As Integer = 3 * ONE_UNIT Private Const SPACE_DELAY As Integer = 7 * ONE_UNIT Private Const FREQUENCY_CHARS As Integer = 1200 Private Const FREQUENCY_OTHERCHARS As Integer = 400 Sub Main() Dim p$, temp$ p = ToMorse("Hel/lo 123 world") temp = Replace(p, "+", "") Debug.Print Replace(temp, "_", "") PlayMorse p End Sub Private Function ToMorse(s As String) As String Dim i&, t$, j& s = UCase(s) For i = 1 To Len(s) j = Asc(Mid(s, i, 1)) Select Case j Case 65 To 90 t = t & Split(MORSE_ALPHA, ",")(j - 65) & "+" Case 48 To 57 t = t & Split(MORSE_NUMERIC, ",")(j - 48) & "+" Case 32 t = t & " " & "+" Case Else t = t & "_" & "+" End Select Next i ToMorse = t End Function Private Sub PlayMorse(s As String) Dim i& For i = 1 To Len(s) Select Case Mid(s, i, 1) Case ".": Beep FREQUENCY_CHARS, BEEP_DOT Case "-": Beep FREQUENCY_CHARS, BEEP_DASH Case "_": Beep FREQUENCY_OTHERCHARS, BEEP_OTHER Case "+": Sleep LETTERS_DELAY Case " ": Sleep SPACE_DELAY End Select Sleep DELAY Next i End Sub
Transform the following Racket implementation into Go, maintaining the same output and logic.
#lang racket (require ffi/unsafe ffi/unsafe/define) (define-ffi-definer defmm (ffi-lib "Winmm")) (defmm midiOutOpen (_fun [h : (_ptr o _int32)] [_int = -1] [_pointer = #f] [_pointer = #f] [_int32 = 0] -> _void -> h)) (defmm midiOutShortMsg (_fun _int32 _int32 -> _void)) (define M (midiOutOpen)) (define (midi x y z) (midiOutShortMsg M (+ x (* 256 y) (* 65536 z)))) (define raw-codes '("a.-|b-...|c-.-.|d-..|e.|f..-.|g--.|h....|i..|j.---|k-.-|l.-..|m--|n-." "|o---|p--.-|q--.-|r.-.|s...|t-|u..-|v...-|w.--|x-..-|y-.--|z--..|1.----" "|2..---|3...--|4....-|5.....|6-....|7--...|8---..|9----.|0-----")) (define codes (for/list ([x (regexp-split #rx"\\|" (string-append* raw-codes))]) (cons (string-ref x 0) (substring x 1)))) (define (morse str [unit 0.1]) (define (sound len) (midi #x90 72 127) (sleep (* len unit)) (midi #x90 72 0) (sleep unit)) (define (play str) (midi #xC0 #x35 0) (for ([c str]) (case c [(#\.) (sound 1)] [(#\-) (sound 3)] [(#\ ) (sleep (* 3 unit))]))) (let* ([str (string-foldcase str)] [str (regexp-replace* #rx"[,: [str (regexp-replace* #rx"[.!?]+" str ".")] [str (string-normalize-spaces str)]) (for ([s (string-split str)]) (define m (string-join (for/list ([c s]) (cond [(assq c codes) => cdr] [else (case c [(#\space) " "] [(#\.) " "] [else ""])])))) (printf "~a: ~a\n" s m) (play (string-append m " "))))) (morse "Say something here")
package main import ( "flag" "fmt" "log" "regexp" "strings" "syscall" "time" "unicode" ) type key struct { duration int on bool sym string } var ( runeToKeys = map[rune][]key{} interCharGap = []key{{1, false, ""}} punctGap = []key{{7, false, " / "}} charGap = []key{{3, false, " "}} wordGap = []key{{7, false, " / "}} ) const rawMorse = ` A:.- J:.--- S:... 1:.---- .:.-.-.-  ::---... B:-... K:-.- T:- 2:..--- ,:--..--  ;:-.-.-. C:-.-. L:.-.. U:..- 3:...--  ?:..--.. =:-...- D:-.. M:-- V:...- 4:....- ':.----. +:.-.-. E:. N:-. W:.-- 5:.....  !:-.-.-- -:-....- F:..-. O:--- X:-..- 6:-.... /:-..-. _:..--.- G:--. P:.--. Y:-.-- 7:--... (:-.--. ":.-..-. H:.... Q:--.- Z:--.. 8:---.. ):-.--.- $:...-..- I:.. R:.-. 0:----- 9:----. &:.-... @:.--.-. ` func init() { r := regexp.MustCompile("([^ ]):([.-]+)") for _, m := range r.FindAllStringSubmatch(rawMorse, -1) { c := m[1][0] keys := []key{} for i, dd := range m[2] { if i > 0 { keys = append(keys, interCharGap...) } if dd == '.' { keys = append(keys, key{1, true, "."}) } else if dd == '-' { keys = append(keys, key{3, true, "-"}) } else { log.Fatalf("found %c in morse for %c", dd, c) } runeToKeys[rune(c)] = keys runeToKeys[unicode.ToLower(rune(c))] = keys } } } func MorseKeys(in string) ([]key, error) { afterWord := false afterChar := false result := []key{} for _, c := range in { if unicode.IsSpace(c) { afterWord = true continue } morse, ok := runeToKeys[c] if !ok { return nil, fmt.Errorf("can't translate %c to morse", c) } if unicode.IsPunct(c) && afterChar { result = append(result, punctGap...) } else if afterWord { result = append(result, wordGap...) } else if afterChar { result = append(result, charGap...) } result = append(result, morse...) afterChar = true afterWord = false } return result, nil } func main() { var ditDuration time.Duration flag.DurationVar(&ditDuration, "d", 40*time.Millisecond, "length of dit") flag.Parse() in := "hello world." if len(flag.Args()) > 1 { in = strings.Join(flag.Args(), " ") } keys, err := MorseKeys(in) if err != nil { log.Fatalf("failed to translate: %s", err) } for _, k := range keys { if k.on { if err := note(true); err != nil { log.Fatalf("failed to play note: %s", err) } } fmt.Print(k.sym) time.Sleep(ditDuration * time.Duration(k.duration)) if k.on { if err := note(false); err != nil { log.Fatalf("failed to stop note: %s", err) } } } fmt.Println() } var consoleFD uintptr func init() { fd, err := syscall.Open("/dev/console", syscall.O_WRONLY, 0) if err != nil { log.Fatalf("failed to get console device: %s", err) } consoleFD = uintptr(fd) } const KIOCSOUND = 0x4B2F const clockTickRate = 1193180 const freqHz = 600 func note(on bool) error { arg := uintptr(0) if on { arg = clockTickRate / freqHz } _, _, errno := syscall.Syscall(syscall.SYS_IOCTL, consoleFD, KIOCSOUND, arg) if errno != 0 { return errno } return nil }
Keep all operations the same but rewrite the snippet in C.
require 'win32/sound' class MorseCode MORSE = { "!" => "---.", "\"" => ".-..-.", "$" => "...-..-", "'" => ".----.", "(" => "-.--.", ")" => "-.--.-", "+" => ".-.-.", "," => "--..--", "-" => "-....-", "." => ".-.-.-", "/" => "-..-.", "0" => "-----", "1" => ".----", "2" => "..---", "3" => "...--", "4" => "....-", "5" => ".....", "6" => "-....", "7" => "--...", "8" => "---..", "9" => "----.", ":" => "---...", ";" => "-.-.-.", "=" => "-...-", "?" => "..--..", "@" => ".--.-.", "A" => ".-", "B" => "-...", "C" => "-.-.", "D" => "-..", "E" => ".", "F" => "..-.", "G" => "--.", "H" => "....", "I" => "..", "J" => ".---", "K" => "-.-", "L" => ".-..", "M" => "--", "N" => "-.", "O" => "---", "P" => ".--.", "Q" => "--.-", "R" => ".-.", "S" => "...", "T" => "-", "U" => "..-", "V" => "...-", "W" => ".--", "X" => "-..-", "Y" => "-.--", "Z" => "--..", "[" => "-.--.", "]" => "-.--.-", "_" => "..--.-", } T_UNIT = 75 FREQ = 700 DIT = 1 * T_UNIT DAH = 3 * T_UNIT CHARGAP = 1 * T_UNIT WORDGAP = 7 * T_UNIT def initialize(string) @message = string puts "your message is end def send @message.strip.upcase.split.each do |word| word.each_char do |char| send_char char pause CHARGAP print " " end pause WORDGAP puts "" end end private def send_char(char) MORSE[char].each_char do |code| case code when '.' then beep DIT when '-' then beep DAH end pause CHARGAP print code end end def beep(ms) ::Win32::Sound.beep(FREQ, ms) end def pause(ms) sleep(ms.to_f/1000.0) end end MorseCode.new('sos').send MorseCode.new('this is a test.').send
#include <ctype.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #define BIND(A,L,H) ((L)<(A)?(A)<(H)?(A):(H):(L)) char dih[50],dah[50],medium[30],word[30], *dd[2] = {dih,dah}; const char *ascii = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789.,?'!/()&:;=+-_\"$@", *itu[] = { "13","3111","3131","311","1","1131","331","1111","11","1333","313","1311","33","31","333","1331","3313","131","111","3","113","1113","133","3113","3133","3311","33333","13333","11333","11133","11113","11111","31111","33111","33311","33331","131313","331133","113311","133331","313133","31131","31331","313313","13111","333111","313131","31113","13131","311113","113313","131131","1113113","133131" }; void append(char*s,const char*morse) { for (; *morse; ++morse) strcat(s,dd['3'==*morse]); strcat(s,medium); } char*translate(const char*i,char*o) { const char*pc; sprintf(o,"beep"); for (; *i; ++i) if (NULL == (pc = strchr(ascii,toupper(*i)))) strcat(o,word); else append(o,itu[pc-ascii]); strcat(o,word); return o; } int main(int ac,char*av[]) { char sin[73],sout[100000]; int dit = 100; if (1 < ac) { if (strlen(av[1]) != strspn(av[1],"0123456789")) return 0*fprintf(stderr,"use: %s [duration] dit in ms, default %d\n",*av,dit); dit = BIND(atoi(av[1]),1,1000); } sprintf(dah," -n -f 440 -l %d -D %d",3*dit,dit); sprintf(dih," -n -f 440 -l %d -D %d",dit,dit); sprintf(medium," -n -D %d",(3-1)*dit); sprintf(word," -n -D %d",(7-(3-1)-1)*dit); while (NULL != fgets(sin,72,stdin)) puts(translate(sin,sout)); return 0; }
Maintain the same structure and functionality when rewriting this code in C#.
require 'win32/sound' class MorseCode MORSE = { "!" => "---.", "\"" => ".-..-.", "$" => "...-..-", "'" => ".----.", "(" => "-.--.", ")" => "-.--.-", "+" => ".-.-.", "," => "--..--", "-" => "-....-", "." => ".-.-.-", "/" => "-..-.", "0" => "-----", "1" => ".----", "2" => "..---", "3" => "...--", "4" => "....-", "5" => ".....", "6" => "-....", "7" => "--...", "8" => "---..", "9" => "----.", ":" => "---...", ";" => "-.-.-.", "=" => "-...-", "?" => "..--..", "@" => ".--.-.", "A" => ".-", "B" => "-...", "C" => "-.-.", "D" => "-..", "E" => ".", "F" => "..-.", "G" => "--.", "H" => "....", "I" => "..", "J" => ".---", "K" => "-.-", "L" => ".-..", "M" => "--", "N" => "-.", "O" => "---", "P" => ".--.", "Q" => "--.-", "R" => ".-.", "S" => "...", "T" => "-", "U" => "..-", "V" => "...-", "W" => ".--", "X" => "-..-", "Y" => "-.--", "Z" => "--..", "[" => "-.--.", "]" => "-.--.-", "_" => "..--.-", } T_UNIT = 75 FREQ = 700 DIT = 1 * T_UNIT DAH = 3 * T_UNIT CHARGAP = 1 * T_UNIT WORDGAP = 7 * T_UNIT def initialize(string) @message = string puts "your message is end def send @message.strip.upcase.split.each do |word| word.each_char do |char| send_char char pause CHARGAP print " " end pause WORDGAP puts "" end end private def send_char(char) MORSE[char].each_char do |code| case code when '.' then beep DIT when '-' then beep DAH end pause CHARGAP print code end end def beep(ms) ::Win32::Sound.beep(FREQ, ms) end def pause(ms) sleep(ms.to_f/1000.0) end end MorseCode.new('sos').send MorseCode.new('this is a test.').send
using System; using System.Collections.Generic; namespace Morse { class Morse { static void Main(string[] args) { string word = "sos"; Dictionary<string, string> Codes = new Dictionary<string, string> { {"a", ".- "}, {"b", "-... "}, {"c", "-.-. "}, {"d", "-.. "}, {"e", ". "}, {"f", "..-. "}, {"g", "--. "}, {"h", ".... "}, {"i", ".. "}, {"j", ".--- "}, {"k", "-.- "}, {"l", ".-.. "}, {"m", "-- "}, {"n", "-. "}, {"o", "--- "}, {"p", ".--. "}, {"q", "--.- "}, {"r", ".-. "}, {"s", "... "}, {"t", "- "}, {"u", "..- "}, {"v", "...- "}, {"w", ".-- "}, {"x", "-..- "}, {"y", "-.-- "}, {"z", "--.. "}, {"0", "-----"}, {"1", ".----"}, {"2", "..---"}, {"3", "...--"}, {"4", "....-"}, {"5", "....."}, {"6", "-...."}, {"7", "--..."}, {"8", "---.."}, {"9", "----."} }; foreach (char c in word.ToCharArray()) { string rslt = Codes[c.ToString()].Trim(); foreach (char c2 in rslt.ToCharArray()) { if (c2 == '.') Console.Beep(1000, 250); else Console.Beep(1000, 750); } System.Threading.Thread.Sleep(50); } } } }
Convert the following code from Ruby to Python, ensuring the logic remains intact.
require 'win32/sound' class MorseCode MORSE = { "!" => "---.", "\"" => ".-..-.", "$" => "...-..-", "'" => ".----.", "(" => "-.--.", ")" => "-.--.-", "+" => ".-.-.", "," => "--..--", "-" => "-....-", "." => ".-.-.-", "/" => "-..-.", "0" => "-----", "1" => ".----", "2" => "..---", "3" => "...--", "4" => "....-", "5" => ".....", "6" => "-....", "7" => "--...", "8" => "---..", "9" => "----.", ":" => "---...", ";" => "-.-.-.", "=" => "-...-", "?" => "..--..", "@" => ".--.-.", "A" => ".-", "B" => "-...", "C" => "-.-.", "D" => "-..", "E" => ".", "F" => "..-.", "G" => "--.", "H" => "....", "I" => "..", "J" => ".---", "K" => "-.-", "L" => ".-..", "M" => "--", "N" => "-.", "O" => "---", "P" => ".--.", "Q" => "--.-", "R" => ".-.", "S" => "...", "T" => "-", "U" => "..-", "V" => "...-", "W" => ".--", "X" => "-..-", "Y" => "-.--", "Z" => "--..", "[" => "-.--.", "]" => "-.--.-", "_" => "..--.-", } T_UNIT = 75 FREQ = 700 DIT = 1 * T_UNIT DAH = 3 * T_UNIT CHARGAP = 1 * T_UNIT WORDGAP = 7 * T_UNIT def initialize(string) @message = string puts "your message is end def send @message.strip.upcase.split.each do |word| word.each_char do |char| send_char char pause CHARGAP print " " end pause WORDGAP puts "" end end private def send_char(char) MORSE[char].each_char do |code| case code when '.' then beep DIT when '-' then beep DAH end pause CHARGAP print code end end def beep(ms) ::Win32::Sound.beep(FREQ, ms) end def pause(ms) sleep(ms.to_f/1000.0) end end MorseCode.new('sos').send MorseCode.new('this is a test.').send
import time, winsound char2morse = { "!": "---.", "\"": ".-..-.", "$": "...-..-", "'": ".----.", "(": "-.--.", ")": "-.--.-", "+": ".-.-.", ",": "--..--", "-": "-....-", ".": ".-.-.-", "/": "-..-.", "0": "-----", "1": ".----", "2": "..---", "3": "...--", "4": "....-", "5": ".....", "6": "-....", "7": "--...", "8": "---..", "9": "----.", ":": "---...", ";": "-.-.-.", "=": "-...-", "?": "..--..", "@": ".--.-.", "A": ".-", "B": "-...", "C": "-.-.", "D": "-..", "E": ".", "F": "..-.", "G": "--.", "H": "....", "I": "..", "J": ".---", "K": "-.-", "L": ".-..", "M": "--", "N": "-.", "O": "---", "P": ".--.", "Q": "--.-", "R": ".-.", "S": "...", "T": "-", "U": "..-", "V": "...-", "W": ".--", "X": "-..-", "Y": "-.--", "Z": "--..", "[": "-.--.", "]": "-.--.-", "_": "..--.-", } e = 50 f = 1280 chargap = 1 wordgap = 7 def gap(n=1): time.sleep(n * e / 1000) off = gap def on(n=1): winsound.Beep(f, n * e) def dit(): on(); off() def dah(): on(3); off() def bloop(n=3): winsound.Beep(f//2, n * e) def windowsmorse(text): for word in text.strip().upper().split(): for char in word: for element in char2morse.get(char, '?'): if element == '-': dah() elif element == '.': dit() else: bloop() gap(chargap) gap(wordgap) while True: windowsmorse(input('A string to change into morse: '))
Can you help me rewrite this code in VB instead of Ruby, keeping it the same logically?
require 'win32/sound' class MorseCode MORSE = { "!" => "---.", "\"" => ".-..-.", "$" => "...-..-", "'" => ".----.", "(" => "-.--.", ")" => "-.--.-", "+" => ".-.-.", "," => "--..--", "-" => "-....-", "." => ".-.-.-", "/" => "-..-.", "0" => "-----", "1" => ".----", "2" => "..---", "3" => "...--", "4" => "....-", "5" => ".....", "6" => "-....", "7" => "--...", "8" => "---..", "9" => "----.", ":" => "---...", ";" => "-.-.-.", "=" => "-...-", "?" => "..--..", "@" => ".--.-.", "A" => ".-", "B" => "-...", "C" => "-.-.", "D" => "-..", "E" => ".", "F" => "..-.", "G" => "--.", "H" => "....", "I" => "..", "J" => ".---", "K" => "-.-", "L" => ".-..", "M" => "--", "N" => "-.", "O" => "---", "P" => ".--.", "Q" => "--.-", "R" => ".-.", "S" => "...", "T" => "-", "U" => "..-", "V" => "...-", "W" => ".--", "X" => "-..-", "Y" => "-.--", "Z" => "--..", "[" => "-.--.", "]" => "-.--.-", "_" => "..--.-", } T_UNIT = 75 FREQ = 700 DIT = 1 * T_UNIT DAH = 3 * T_UNIT CHARGAP = 1 * T_UNIT WORDGAP = 7 * T_UNIT def initialize(string) @message = string puts "your message is end def send @message.strip.upcase.split.each do |word| word.each_char do |char| send_char char pause CHARGAP print " " end pause WORDGAP puts "" end end private def send_char(char) MORSE[char].each_char do |code| case code when '.' then beep DIT when '-' then beep DAH end pause CHARGAP print code end end def beep(ms) ::Win32::Sound.beep(FREQ, ms) end def pause(ms) sleep(ms.to_f/1000.0) end end MorseCode.new('sos').send MorseCode.new('this is a test.').send
Option Explicit Private Declare Function Beep Lib "kernel32" (ByVal dwFreq As Long, ByVal dwDuration As Long) As Long Private Declare Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As Long) Private Const MORSE_ALPHA As String = ".-,-...,-.-.,-..,.,..-.,--.,....,..,.---,-.-,.-..,--,-.,---,.--.,--.-,.-.,...,-,..-,...-,.--,-..-,-.--,--.." Private Const MORSE_NUMERIC As String = "-----,.----,..---,...--,....-,.....,-....,--...,---..,----." Private Const ONE_UNIT As Integer = 100 Private Const BEEP_DOT As Integer = ONE_UNIT Private Const BEEP_DASH As Integer = 3 * ONE_UNIT Private Const BEEP_OTHER As Integer = 7 * ONE_UNIT Private Const DELAY As Integer = ONE_UNIT Private Const LETTERS_DELAY As Integer = 3 * ONE_UNIT Private Const SPACE_DELAY As Integer = 7 * ONE_UNIT Private Const FREQUENCY_CHARS As Integer = 1200 Private Const FREQUENCY_OTHERCHARS As Integer = 400 Sub Main() Dim p$, temp$ p = ToMorse("Hel/lo 123 world") temp = Replace(p, "+", "") Debug.Print Replace(temp, "_", "") PlayMorse p End Sub Private Function ToMorse(s As String) As String Dim i&, t$, j& s = UCase(s) For i = 1 To Len(s) j = Asc(Mid(s, i, 1)) Select Case j Case 65 To 90 t = t & Split(MORSE_ALPHA, ",")(j - 65) & "+" Case 48 To 57 t = t & Split(MORSE_NUMERIC, ",")(j - 48) & "+" Case 32 t = t & " " & "+" Case Else t = t & "_" & "+" End Select Next i ToMorse = t End Function Private Sub PlayMorse(s As String) Dim i& For i = 1 To Len(s) Select Case Mid(s, i, 1) Case ".": Beep FREQUENCY_CHARS, BEEP_DOT Case "-": Beep FREQUENCY_CHARS, BEEP_DASH Case "_": Beep FREQUENCY_OTHERCHARS, BEEP_OTHER Case "+": Sleep LETTERS_DELAY Case " ": Sleep SPACE_DELAY End Select Sleep DELAY Next i End Sub
Port the provided Ruby code into Go while preserving the original functionality.
require 'win32/sound' class MorseCode MORSE = { "!" => "---.", "\"" => ".-..-.", "$" => "...-..-", "'" => ".----.", "(" => "-.--.", ")" => "-.--.-", "+" => ".-.-.", "," => "--..--", "-" => "-....-", "." => ".-.-.-", "/" => "-..-.", "0" => "-----", "1" => ".----", "2" => "..---", "3" => "...--", "4" => "....-", "5" => ".....", "6" => "-....", "7" => "--...", "8" => "---..", "9" => "----.", ":" => "---...", ";" => "-.-.-.", "=" => "-...-", "?" => "..--..", "@" => ".--.-.", "A" => ".-", "B" => "-...", "C" => "-.-.", "D" => "-..", "E" => ".", "F" => "..-.", "G" => "--.", "H" => "....", "I" => "..", "J" => ".---", "K" => "-.-", "L" => ".-..", "M" => "--", "N" => "-.", "O" => "---", "P" => ".--.", "Q" => "--.-", "R" => ".-.", "S" => "...", "T" => "-", "U" => "..-", "V" => "...-", "W" => ".--", "X" => "-..-", "Y" => "-.--", "Z" => "--..", "[" => "-.--.", "]" => "-.--.-", "_" => "..--.-", } T_UNIT = 75 FREQ = 700 DIT = 1 * T_UNIT DAH = 3 * T_UNIT CHARGAP = 1 * T_UNIT WORDGAP = 7 * T_UNIT def initialize(string) @message = string puts "your message is end def send @message.strip.upcase.split.each do |word| word.each_char do |char| send_char char pause CHARGAP print " " end pause WORDGAP puts "" end end private def send_char(char) MORSE[char].each_char do |code| case code when '.' then beep DIT when '-' then beep DAH end pause CHARGAP print code end end def beep(ms) ::Win32::Sound.beep(FREQ, ms) end def pause(ms) sleep(ms.to_f/1000.0) end end MorseCode.new('sos').send MorseCode.new('this is a test.').send
package main import ( "flag" "fmt" "log" "regexp" "strings" "syscall" "time" "unicode" ) type key struct { duration int on bool sym string } var ( runeToKeys = map[rune][]key{} interCharGap = []key{{1, false, ""}} punctGap = []key{{7, false, " / "}} charGap = []key{{3, false, " "}} wordGap = []key{{7, false, " / "}} ) const rawMorse = ` A:.- J:.--- S:... 1:.---- .:.-.-.-  ::---... B:-... K:-.- T:- 2:..--- ,:--..--  ;:-.-.-. C:-.-. L:.-.. U:..- 3:...--  ?:..--.. =:-...- D:-.. M:-- V:...- 4:....- ':.----. +:.-.-. E:. N:-. W:.-- 5:.....  !:-.-.-- -:-....- F:..-. O:--- X:-..- 6:-.... /:-..-. _:..--.- G:--. P:.--. Y:-.-- 7:--... (:-.--. ":.-..-. H:.... Q:--.- Z:--.. 8:---.. ):-.--.- $:...-..- I:.. R:.-. 0:----- 9:----. &:.-... @:.--.-. ` func init() { r := regexp.MustCompile("([^ ]):([.-]+)") for _, m := range r.FindAllStringSubmatch(rawMorse, -1) { c := m[1][0] keys := []key{} for i, dd := range m[2] { if i > 0 { keys = append(keys, interCharGap...) } if dd == '.' { keys = append(keys, key{1, true, "."}) } else if dd == '-' { keys = append(keys, key{3, true, "-"}) } else { log.Fatalf("found %c in morse for %c", dd, c) } runeToKeys[rune(c)] = keys runeToKeys[unicode.ToLower(rune(c))] = keys } } } func MorseKeys(in string) ([]key, error) { afterWord := false afterChar := false result := []key{} for _, c := range in { if unicode.IsSpace(c) { afterWord = true continue } morse, ok := runeToKeys[c] if !ok { return nil, fmt.Errorf("can't translate %c to morse", c) } if unicode.IsPunct(c) && afterChar { result = append(result, punctGap...) } else if afterWord { result = append(result, wordGap...) } else if afterChar { result = append(result, charGap...) } result = append(result, morse...) afterChar = true afterWord = false } return result, nil } func main() { var ditDuration time.Duration flag.DurationVar(&ditDuration, "d", 40*time.Millisecond, "length of dit") flag.Parse() in := "hello world." if len(flag.Args()) > 1 { in = strings.Join(flag.Args(), " ") } keys, err := MorseKeys(in) if err != nil { log.Fatalf("failed to translate: %s", err) } for _, k := range keys { if k.on { if err := note(true); err != nil { log.Fatalf("failed to play note: %s", err) } } fmt.Print(k.sym) time.Sleep(ditDuration * time.Duration(k.duration)) if k.on { if err := note(false); err != nil { log.Fatalf("failed to stop note: %s", err) } } } fmt.Println() } var consoleFD uintptr func init() { fd, err := syscall.Open("/dev/console", syscall.O_WRONLY, 0) if err != nil { log.Fatalf("failed to get console device: %s", err) } consoleFD = uintptr(fd) } const KIOCSOUND = 0x4B2F const clockTickRate = 1193180 const freqHz = 600 func note(on bool) error { arg := uintptr(0) if on { arg = clockTickRate / freqHz } _, _, errno := syscall.Syscall(syscall.SYS_IOCTL, consoleFD, KIOCSOUND, arg) if errno != 0 { return errno } return nil }
Transform the following Scala implementation into C, maintaining the same output and logic.
import javax.sound.sampled.AudioFormat import javax.sound.sampled.AudioSystem val morseCode = hashMapOf( 'a' to ".-", 'b' to "-...", 'c' to "-.-.", 'd' to "-..", 'e' to ".", 'f' to "..-.", 'g' to "--.", 'h' to "....", 'i' to "..", 'j' to ".---", 'k' to "-.-", 'l' to ".-..", 'm' to "--", 'n' to "-.", 'o' to "---", 'p' to ".--.", 'q' to "--.-", 'r' to ".-.", 's' to "...", 't' to "-", 'u' to "..-", 'v' to "...-", 'w' to ".--", 'x' to "-..-", 'y' to "-.--", 'z' to "--..", '0' to ".....", '1' to "-....", '2' to "--...", '3' to "---..", '4' to "----.", '5' to "-----", '6' to ".----", '7' to "..---", '8' to "...--", '9' to "....-", ' ' to "/", ',' to "--..--", '!' to "-.-.--", '"' to ".-..-.", '.' to ".-.-.-", '?' to "..--..", '\'' to ".----.", '/' to "-..-.", '-' to "-....-", '(' to "-.--.-", ')' to "-.--.-" ) val symbolDurationInMs = hashMapOf('.' to 200, '-' to 500, '/' to 1000) fun toMorseCode(message: String) = message.filter { morseCode.containsKey(it) } .fold("") { acc, ch -> acc + morseCode[ch]!! } fun playMorseCode(morseCode: String) = morseCode.forEach { symbol -> beep(symbolDurationInMs[symbol]!!) } fun beep(durationInMs: Int) { val soundBuffer = ByteArray(durationInMs * 8) for ((i, _) in soundBuffer.withIndex()) { soundBuffer[i] = (Math.sin(i / 8.0 * 2.0 * Math.PI) * 80.0).toByte() } val audioFormat = AudioFormat( 8000F, 8, 1, true, false ) with (AudioSystem.getSourceDataLine(audioFormat)!!) { open(audioFormat) start() write(soundBuffer, 0, soundBuffer.size) drain() close() } } fun main(args: Array<String>) { args.forEach { playMorseCode(toMorseCode(it.toLowerCase())) } }
#include <ctype.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #define BIND(A,L,H) ((L)<(A)?(A)<(H)?(A):(H):(L)) char dih[50],dah[50],medium[30],word[30], *dd[2] = {dih,dah}; const char *ascii = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789.,?'!/()&:;=+-_\"$@", *itu[] = { "13","3111","3131","311","1","1131","331","1111","11","1333","313","1311","33","31","333","1331","3313","131","111","3","113","1113","133","3113","3133","3311","33333","13333","11333","11133","11113","11111","31111","33111","33311","33331","131313","331133","113311","133331","313133","31131","31331","313313","13111","333111","313131","31113","13131","311113","113313","131131","1113113","133131" }; void append(char*s,const char*morse) { for (; *morse; ++morse) strcat(s,dd['3'==*morse]); strcat(s,medium); } char*translate(const char*i,char*o) { const char*pc; sprintf(o,"beep"); for (; *i; ++i) if (NULL == (pc = strchr(ascii,toupper(*i)))) strcat(o,word); else append(o,itu[pc-ascii]); strcat(o,word); return o; } int main(int ac,char*av[]) { char sin[73],sout[100000]; int dit = 100; if (1 < ac) { if (strlen(av[1]) != strspn(av[1],"0123456789")) return 0*fprintf(stderr,"use: %s [duration] dit in ms, default %d\n",*av,dit); dit = BIND(atoi(av[1]),1,1000); } sprintf(dah," -n -f 440 -l %d -D %d",3*dit,dit); sprintf(dih," -n -f 440 -l %d -D %d",dit,dit); sprintf(medium," -n -D %d",(3-1)*dit); sprintf(word," -n -D %d",(7-(3-1)-1)*dit); while (NULL != fgets(sin,72,stdin)) puts(translate(sin,sout)); return 0; }
Please provide an equivalent version of this Scala code in C#.
import javax.sound.sampled.AudioFormat import javax.sound.sampled.AudioSystem val morseCode = hashMapOf( 'a' to ".-", 'b' to "-...", 'c' to "-.-.", 'd' to "-..", 'e' to ".", 'f' to "..-.", 'g' to "--.", 'h' to "....", 'i' to "..", 'j' to ".---", 'k' to "-.-", 'l' to ".-..", 'm' to "--", 'n' to "-.", 'o' to "---", 'p' to ".--.", 'q' to "--.-", 'r' to ".-.", 's' to "...", 't' to "-", 'u' to "..-", 'v' to "...-", 'w' to ".--", 'x' to "-..-", 'y' to "-.--", 'z' to "--..", '0' to ".....", '1' to "-....", '2' to "--...", '3' to "---..", '4' to "----.", '5' to "-----", '6' to ".----", '7' to "..---", '8' to "...--", '9' to "....-", ' ' to "/", ',' to "--..--", '!' to "-.-.--", '"' to ".-..-.", '.' to ".-.-.-", '?' to "..--..", '\'' to ".----.", '/' to "-..-.", '-' to "-....-", '(' to "-.--.-", ')' to "-.--.-" ) val symbolDurationInMs = hashMapOf('.' to 200, '-' to 500, '/' to 1000) fun toMorseCode(message: String) = message.filter { morseCode.containsKey(it) } .fold("") { acc, ch -> acc + morseCode[ch]!! } fun playMorseCode(morseCode: String) = morseCode.forEach { symbol -> beep(symbolDurationInMs[symbol]!!) } fun beep(durationInMs: Int) { val soundBuffer = ByteArray(durationInMs * 8) for ((i, _) in soundBuffer.withIndex()) { soundBuffer[i] = (Math.sin(i / 8.0 * 2.0 * Math.PI) * 80.0).toByte() } val audioFormat = AudioFormat( 8000F, 8, 1, true, false ) with (AudioSystem.getSourceDataLine(audioFormat)!!) { open(audioFormat) start() write(soundBuffer, 0, soundBuffer.size) drain() close() } } fun main(args: Array<String>) { args.forEach { playMorseCode(toMorseCode(it.toLowerCase())) } }
using System; using System.Collections.Generic; namespace Morse { class Morse { static void Main(string[] args) { string word = "sos"; Dictionary<string, string> Codes = new Dictionary<string, string> { {"a", ".- "}, {"b", "-... "}, {"c", "-.-. "}, {"d", "-.. "}, {"e", ". "}, {"f", "..-. "}, {"g", "--. "}, {"h", ".... "}, {"i", ".. "}, {"j", ".--- "}, {"k", "-.- "}, {"l", ".-.. "}, {"m", "-- "}, {"n", "-. "}, {"o", "--- "}, {"p", ".--. "}, {"q", "--.- "}, {"r", ".-. "}, {"s", "... "}, {"t", "- "}, {"u", "..- "}, {"v", "...- "}, {"w", ".-- "}, {"x", "-..- "}, {"y", "-.-- "}, {"z", "--.. "}, {"0", "-----"}, {"1", ".----"}, {"2", "..---"}, {"3", "...--"}, {"4", "....-"}, {"5", "....."}, {"6", "-...."}, {"7", "--..."}, {"8", "---.."}, {"9", "----."} }; foreach (char c in word.ToCharArray()) { string rslt = Codes[c.ToString()].Trim(); foreach (char c2 in rslt.ToCharArray()) { if (c2 == '.') Console.Beep(1000, 250); else Console.Beep(1000, 750); } System.Threading.Thread.Sleep(50); } } } }
Port the following code from Scala to Java with equivalent syntax and logic.
import javax.sound.sampled.AudioFormat import javax.sound.sampled.AudioSystem val morseCode = hashMapOf( 'a' to ".-", 'b' to "-...", 'c' to "-.-.", 'd' to "-..", 'e' to ".", 'f' to "..-.", 'g' to "--.", 'h' to "....", 'i' to "..", 'j' to ".---", 'k' to "-.-", 'l' to ".-..", 'm' to "--", 'n' to "-.", 'o' to "---", 'p' to ".--.", 'q' to "--.-", 'r' to ".-.", 's' to "...", 't' to "-", 'u' to "..-", 'v' to "...-", 'w' to ".--", 'x' to "-..-", 'y' to "-.--", 'z' to "--..", '0' to ".....", '1' to "-....", '2' to "--...", '3' to "---..", '4' to "----.", '5' to "-----", '6' to ".----", '7' to "..---", '8' to "...--", '9' to "....-", ' ' to "/", ',' to "--..--", '!' to "-.-.--", '"' to ".-..-.", '.' to ".-.-.-", '?' to "..--..", '\'' to ".----.", '/' to "-..-.", '-' to "-....-", '(' to "-.--.-", ')' to "-.--.-" ) val symbolDurationInMs = hashMapOf('.' to 200, '-' to 500, '/' to 1000) fun toMorseCode(message: String) = message.filter { morseCode.containsKey(it) } .fold("") { acc, ch -> acc + morseCode[ch]!! } fun playMorseCode(morseCode: String) = morseCode.forEach { symbol -> beep(symbolDurationInMs[symbol]!!) } fun beep(durationInMs: Int) { val soundBuffer = ByteArray(durationInMs * 8) for ((i, _) in soundBuffer.withIndex()) { soundBuffer[i] = (Math.sin(i / 8.0 * 2.0 * Math.PI) * 80.0).toByte() } val audioFormat = AudioFormat( 8000F, 8, 1, true, false ) with (AudioSystem.getSourceDataLine(audioFormat)!!) { open(audioFormat) start() write(soundBuffer, 0, soundBuffer.size) drain() close() } } fun main(args: Array<String>) { args.forEach { playMorseCode(toMorseCode(it.toLowerCase())) } }
import java.util.*; public class MorseCode { final static String[][] code = { {"A", ".- "}, {"B", "-... "}, {"C", "-.-. "}, {"D", "-.. "}, {"E", ". "}, {"F", "..-. "}, {"G", "--. "}, {"H", ".... "}, {"I", ".. "}, {"J", ".--- "}, {"K", "-.- "}, {"L", ".-.. "}, {"M", "-- "}, {"N", "-. "}, {"O", "--- "}, {"P", ".--. "}, {"Q", "--.- "}, {"R", ".-. "}, {"S", "... "}, {"T", "- "}, {"U", "..- "}, {"V", "...- "}, {"W", ".- - "}, {"X", "-..- "}, {"Y", "-.-- "}, {"Z", "--.. "}, {"0", "----- "}, {"1", ".---- "}, {"2", "..--- "}, {"3", "...-- "}, {"4", "....- "}, {"5", "..... "}, {"6", "-.... "}, {"7", "--... "}, {"8", "---.. "}, {"9", "----. "}, {"'", ".----. "}, {":", "---... "}, {",", "--..-- "}, {"-", "-....- "}, {"(", "-.--.- "}, {".", ".-.-.- "}, {"?", "..--.. "}, {";", "-.-.-. "}, {"/", "-..-. "}, {"-", "..--.- "}, {")", "---.. "}, {"=", "-...- "}, {"@", ".--.-. "}, {"\"", ".-..-."}, {"+", ".-.-. "}, {" ", "/"}}; final static Map<Character, String> map = new HashMap<>(); static { for (String[] pair : code) map.put(pair[0].charAt(0), pair[1].trim()); } public static void main(String[] args) { printMorse("sos"); printMorse(" Hello World!"); printMorse("Rosetta Code"); } static void printMorse(String input) { System.out.printf("%s %n", input); input = input.trim().replaceAll("[ ]+", " ").toUpperCase(); for (char c : input.toCharArray()) { String s = map.get(c); if (s != null) System.out.printf("%s ", s); } System.out.println("\n"); } }
Translate this program into Python but keep the logic exactly as in Scala.
import javax.sound.sampled.AudioFormat import javax.sound.sampled.AudioSystem val morseCode = hashMapOf( 'a' to ".-", 'b' to "-...", 'c' to "-.-.", 'd' to "-..", 'e' to ".", 'f' to "..-.", 'g' to "--.", 'h' to "....", 'i' to "..", 'j' to ".---", 'k' to "-.-", 'l' to ".-..", 'm' to "--", 'n' to "-.", 'o' to "---", 'p' to ".--.", 'q' to "--.-", 'r' to ".-.", 's' to "...", 't' to "-", 'u' to "..-", 'v' to "...-", 'w' to ".--", 'x' to "-..-", 'y' to "-.--", 'z' to "--..", '0' to ".....", '1' to "-....", '2' to "--...", '3' to "---..", '4' to "----.", '5' to "-----", '6' to ".----", '7' to "..---", '8' to "...--", '9' to "....-", ' ' to "/", ',' to "--..--", '!' to "-.-.--", '"' to ".-..-.", '.' to ".-.-.-", '?' to "..--..", '\'' to ".----.", '/' to "-..-.", '-' to "-....-", '(' to "-.--.-", ')' to "-.--.-" ) val symbolDurationInMs = hashMapOf('.' to 200, '-' to 500, '/' to 1000) fun toMorseCode(message: String) = message.filter { morseCode.containsKey(it) } .fold("") { acc, ch -> acc + morseCode[ch]!! } fun playMorseCode(morseCode: String) = morseCode.forEach { symbol -> beep(symbolDurationInMs[symbol]!!) } fun beep(durationInMs: Int) { val soundBuffer = ByteArray(durationInMs * 8) for ((i, _) in soundBuffer.withIndex()) { soundBuffer[i] = (Math.sin(i / 8.0 * 2.0 * Math.PI) * 80.0).toByte() } val audioFormat = AudioFormat( 8000F, 8, 1, true, false ) with (AudioSystem.getSourceDataLine(audioFormat)!!) { open(audioFormat) start() write(soundBuffer, 0, soundBuffer.size) drain() close() } } fun main(args: Array<String>) { args.forEach { playMorseCode(toMorseCode(it.toLowerCase())) } }
import time, winsound char2morse = { "!": "---.", "\"": ".-..-.", "$": "...-..-", "'": ".----.", "(": "-.--.", ")": "-.--.-", "+": ".-.-.", ",": "--..--", "-": "-....-", ".": ".-.-.-", "/": "-..-.", "0": "-----", "1": ".----", "2": "..---", "3": "...--", "4": "....-", "5": ".....", "6": "-....", "7": "--...", "8": "---..", "9": "----.", ":": "---...", ";": "-.-.-.", "=": "-...-", "?": "..--..", "@": ".--.-.", "A": ".-", "B": "-...", "C": "-.-.", "D": "-..", "E": ".", "F": "..-.", "G": "--.", "H": "....", "I": "..", "J": ".---", "K": "-.-", "L": ".-..", "M": "--", "N": "-.", "O": "---", "P": ".--.", "Q": "--.-", "R": ".-.", "S": "...", "T": "-", "U": "..-", "V": "...-", "W": ".--", "X": "-..-", "Y": "-.--", "Z": "--..", "[": "-.--.", "]": "-.--.-", "_": "..--.-", } e = 50 f = 1280 chargap = 1 wordgap = 7 def gap(n=1): time.sleep(n * e / 1000) off = gap def on(n=1): winsound.Beep(f, n * e) def dit(): on(); off() def dah(): on(3); off() def bloop(n=3): winsound.Beep(f//2, n * e) def windowsmorse(text): for word in text.strip().upper().split(): for char in word: for element in char2morse.get(char, '?'): if element == '-': dah() elif element == '.': dit() else: bloop() gap(chargap) gap(wordgap) while True: windowsmorse(input('A string to change into morse: '))
Write the same code in VB as shown below in Scala.
import javax.sound.sampled.AudioFormat import javax.sound.sampled.AudioSystem val morseCode = hashMapOf( 'a' to ".-", 'b' to "-...", 'c' to "-.-.", 'd' to "-..", 'e' to ".", 'f' to "..-.", 'g' to "--.", 'h' to "....", 'i' to "..", 'j' to ".---", 'k' to "-.-", 'l' to ".-..", 'm' to "--", 'n' to "-.", 'o' to "---", 'p' to ".--.", 'q' to "--.-", 'r' to ".-.", 's' to "...", 't' to "-", 'u' to "..-", 'v' to "...-", 'w' to ".--", 'x' to "-..-", 'y' to "-.--", 'z' to "--..", '0' to ".....", '1' to "-....", '2' to "--...", '3' to "---..", '4' to "----.", '5' to "-----", '6' to ".----", '7' to "..---", '8' to "...--", '9' to "....-", ' ' to "/", ',' to "--..--", '!' to "-.-.--", '"' to ".-..-.", '.' to ".-.-.-", '?' to "..--..", '\'' to ".----.", '/' to "-..-.", '-' to "-....-", '(' to "-.--.-", ')' to "-.--.-" ) val symbolDurationInMs = hashMapOf('.' to 200, '-' to 500, '/' to 1000) fun toMorseCode(message: String) = message.filter { morseCode.containsKey(it) } .fold("") { acc, ch -> acc + morseCode[ch]!! } fun playMorseCode(morseCode: String) = morseCode.forEach { symbol -> beep(symbolDurationInMs[symbol]!!) } fun beep(durationInMs: Int) { val soundBuffer = ByteArray(durationInMs * 8) for ((i, _) in soundBuffer.withIndex()) { soundBuffer[i] = (Math.sin(i / 8.0 * 2.0 * Math.PI) * 80.0).toByte() } val audioFormat = AudioFormat( 8000F, 8, 1, true, false ) with (AudioSystem.getSourceDataLine(audioFormat)!!) { open(audioFormat) start() write(soundBuffer, 0, soundBuffer.size) drain() close() } } fun main(args: Array<String>) { args.forEach { playMorseCode(toMorseCode(it.toLowerCase())) } }
Option Explicit Private Declare Function Beep Lib "kernel32" (ByVal dwFreq As Long, ByVal dwDuration As Long) As Long Private Declare Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As Long) Private Const MORSE_ALPHA As String = ".-,-...,-.-.,-..,.,..-.,--.,....,..,.---,-.-,.-..,--,-.,---,.--.,--.-,.-.,...,-,..-,...-,.--,-..-,-.--,--.." Private Const MORSE_NUMERIC As String = "-----,.----,..---,...--,....-,.....,-....,--...,---..,----." Private Const ONE_UNIT As Integer = 100 Private Const BEEP_DOT As Integer = ONE_UNIT Private Const BEEP_DASH As Integer = 3 * ONE_UNIT Private Const BEEP_OTHER As Integer = 7 * ONE_UNIT Private Const DELAY As Integer = ONE_UNIT Private Const LETTERS_DELAY As Integer = 3 * ONE_UNIT Private Const SPACE_DELAY As Integer = 7 * ONE_UNIT Private Const FREQUENCY_CHARS As Integer = 1200 Private Const FREQUENCY_OTHERCHARS As Integer = 400 Sub Main() Dim p$, temp$ p = ToMorse("Hel/lo 123 world") temp = Replace(p, "+", "") Debug.Print Replace(temp, "_", "") PlayMorse p End Sub Private Function ToMorse(s As String) As String Dim i&, t$, j& s = UCase(s) For i = 1 To Len(s) j = Asc(Mid(s, i, 1)) Select Case j Case 65 To 90 t = t & Split(MORSE_ALPHA, ",")(j - 65) & "+" Case 48 To 57 t = t & Split(MORSE_NUMERIC, ",")(j - 48) & "+" Case 32 t = t & " " & "+" Case Else t = t & "_" & "+" End Select Next i ToMorse = t End Function Private Sub PlayMorse(s As String) Dim i& For i = 1 To Len(s) Select Case Mid(s, i, 1) Case ".": Beep FREQUENCY_CHARS, BEEP_DOT Case "-": Beep FREQUENCY_CHARS, BEEP_DASH Case "_": Beep FREQUENCY_OTHERCHARS, BEEP_OTHER Case "+": Sleep LETTERS_DELAY Case " ": Sleep SPACE_DELAY End Select Sleep DELAY Next i End Sub
Please provide an equivalent version of this Scala code in Go.
import javax.sound.sampled.AudioFormat import javax.sound.sampled.AudioSystem val morseCode = hashMapOf( 'a' to ".-", 'b' to "-...", 'c' to "-.-.", 'd' to "-..", 'e' to ".", 'f' to "..-.", 'g' to "--.", 'h' to "....", 'i' to "..", 'j' to ".---", 'k' to "-.-", 'l' to ".-..", 'm' to "--", 'n' to "-.", 'o' to "---", 'p' to ".--.", 'q' to "--.-", 'r' to ".-.", 's' to "...", 't' to "-", 'u' to "..-", 'v' to "...-", 'w' to ".--", 'x' to "-..-", 'y' to "-.--", 'z' to "--..", '0' to ".....", '1' to "-....", '2' to "--...", '3' to "---..", '4' to "----.", '5' to "-----", '6' to ".----", '7' to "..---", '8' to "...--", '9' to "....-", ' ' to "/", ',' to "--..--", '!' to "-.-.--", '"' to ".-..-.", '.' to ".-.-.-", '?' to "..--..", '\'' to ".----.", '/' to "-..-.", '-' to "-....-", '(' to "-.--.-", ')' to "-.--.-" ) val symbolDurationInMs = hashMapOf('.' to 200, '-' to 500, '/' to 1000) fun toMorseCode(message: String) = message.filter { morseCode.containsKey(it) } .fold("") { acc, ch -> acc + morseCode[ch]!! } fun playMorseCode(morseCode: String) = morseCode.forEach { symbol -> beep(symbolDurationInMs[symbol]!!) } fun beep(durationInMs: Int) { val soundBuffer = ByteArray(durationInMs * 8) for ((i, _) in soundBuffer.withIndex()) { soundBuffer[i] = (Math.sin(i / 8.0 * 2.0 * Math.PI) * 80.0).toByte() } val audioFormat = AudioFormat( 8000F, 8, 1, true, false ) with (AudioSystem.getSourceDataLine(audioFormat)!!) { open(audioFormat) start() write(soundBuffer, 0, soundBuffer.size) drain() close() } } fun main(args: Array<String>) { args.forEach { playMorseCode(toMorseCode(it.toLowerCase())) } }
package main import ( "flag" "fmt" "log" "regexp" "strings" "syscall" "time" "unicode" ) type key struct { duration int on bool sym string } var ( runeToKeys = map[rune][]key{} interCharGap = []key{{1, false, ""}} punctGap = []key{{7, false, " / "}} charGap = []key{{3, false, " "}} wordGap = []key{{7, false, " / "}} ) const rawMorse = ` A:.- J:.--- S:... 1:.---- .:.-.-.-  ::---... B:-... K:-.- T:- 2:..--- ,:--..--  ;:-.-.-. C:-.-. L:.-.. U:..- 3:...--  ?:..--.. =:-...- D:-.. M:-- V:...- 4:....- ':.----. +:.-.-. E:. N:-. W:.-- 5:.....  !:-.-.-- -:-....- F:..-. O:--- X:-..- 6:-.... /:-..-. _:..--.- G:--. P:.--. Y:-.-- 7:--... (:-.--. ":.-..-. H:.... Q:--.- Z:--.. 8:---.. ):-.--.- $:...-..- I:.. R:.-. 0:----- 9:----. &:.-... @:.--.-. ` func init() { r := regexp.MustCompile("([^ ]):([.-]+)") for _, m := range r.FindAllStringSubmatch(rawMorse, -1) { c := m[1][0] keys := []key{} for i, dd := range m[2] { if i > 0 { keys = append(keys, interCharGap...) } if dd == '.' { keys = append(keys, key{1, true, "."}) } else if dd == '-' { keys = append(keys, key{3, true, "-"}) } else { log.Fatalf("found %c in morse for %c", dd, c) } runeToKeys[rune(c)] = keys runeToKeys[unicode.ToLower(rune(c))] = keys } } } func MorseKeys(in string) ([]key, error) { afterWord := false afterChar := false result := []key{} for _, c := range in { if unicode.IsSpace(c) { afterWord = true continue } morse, ok := runeToKeys[c] if !ok { return nil, fmt.Errorf("can't translate %c to morse", c) } if unicode.IsPunct(c) && afterChar { result = append(result, punctGap...) } else if afterWord { result = append(result, wordGap...) } else if afterChar { result = append(result, charGap...) } result = append(result, morse...) afterChar = true afterWord = false } return result, nil } func main() { var ditDuration time.Duration flag.DurationVar(&ditDuration, "d", 40*time.Millisecond, "length of dit") flag.Parse() in := "hello world." if len(flag.Args()) > 1 { in = strings.Join(flag.Args(), " ") } keys, err := MorseKeys(in) if err != nil { log.Fatalf("failed to translate: %s", err) } for _, k := range keys { if k.on { if err := note(true); err != nil { log.Fatalf("failed to play note: %s", err) } } fmt.Print(k.sym) time.Sleep(ditDuration * time.Duration(k.duration)) if k.on { if err := note(false); err != nil { log.Fatalf("failed to stop note: %s", err) } } } fmt.Println() } var consoleFD uintptr func init() { fd, err := syscall.Open("/dev/console", syscall.O_WRONLY, 0) if err != nil { log.Fatalf("failed to get console device: %s", err) } consoleFD = uintptr(fd) } const KIOCSOUND = 0x4B2F const clockTickRate = 1193180 const freqHz = 600 func note(on bool) error { arg := uintptr(0) if on { arg = clockTickRate / freqHz } _, _, errno := syscall.Syscall(syscall.SYS_IOCTL, consoleFD, KIOCSOUND, arg) if errno != 0 { return errno } return nil }
Generate a C translation of this Tcl snippet without changing its computational steps.
package require sound proc pause n { global t after [expr {$t * $n}] set ok 1 vwait ok } proc beep n { global frequency set f [snack::filter generator $frequency 30000 0.0 sine -1] set s [snack::sound -rate 22050] $s play -filter $f pause $n $s stop $s destroy $f destroy pause 1 } interp alias {} dit {} beep 1 interp alias {} dah {} beep 3 set MORSE_CODE { "!" "---." "\"" ".-..-." "$" "...-..-" "'" ".----." "(" "-.--." ")" "-.--.-" "+" ".-.-." "," "--..--" "-" "-....-" "." ".-.-.-" "/" "-..-." ":" "---..." ";" "-.-.-." "=" "-...-" "?" "..--.." "@" ".--.-." "[" "-.--." "]" "-.--.-" "_" "..--.-" "0" "-----" "1" ".----" "2" "..---" "3" "...--" "4" "....-" "5" "....." "6" "-...." "7" "--..." "8" "---.." "9" "----." "A" ".-" "B" "-..." "C" "-.-." "D" "-.." "E" "." "F" "..-." "G" "--." "H" "...." "I" ".." "J" ".---" "K" "-.-" "L" ".-.." "M" "--" "N" "-." "O" "---" "P" ".--." "Q" "--.-" "R" ".-." "S" "..." "T" "-" "U" "..-" "V" "...-" "W" ".--" "X" "-..-" "Y" "-.--" "Z" "--.." } proc morse {str wpm} { global t MORSE_CODE set t [expr {1200 / $wpm}] set map {"\\" {} " " {[pause 4]}} foreach {from to} $MORSE_CODE {lappend map $from "$to\[pause 3\]"} set s [string map $map [string toupper $str]] subst [string map {"." [dit] "-" [dah]} $s] return } set frequency 700 morse "Morse code with Tcl and Snack." 20
#include <ctype.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #define BIND(A,L,H) ((L)<(A)?(A)<(H)?(A):(H):(L)) char dih[50],dah[50],medium[30],word[30], *dd[2] = {dih,dah}; const char *ascii = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789.,?'!/()&:;=+-_\"$@", *itu[] = { "13","3111","3131","311","1","1131","331","1111","11","1333","313","1311","33","31","333","1331","3313","131","111","3","113","1113","133","3113","3133","3311","33333","13333","11333","11133","11113","11111","31111","33111","33311","33331","131313","331133","113311","133331","313133","31131","31331","313313","13111","333111","313131","31113","13131","311113","113313","131131","1113113","133131" }; void append(char*s,const char*morse) { for (; *morse; ++morse) strcat(s,dd['3'==*morse]); strcat(s,medium); } char*translate(const char*i,char*o) { const char*pc; sprintf(o,"beep"); for (; *i; ++i) if (NULL == (pc = strchr(ascii,toupper(*i)))) strcat(o,word); else append(o,itu[pc-ascii]); strcat(o,word); return o; } int main(int ac,char*av[]) { char sin[73],sout[100000]; int dit = 100; if (1 < ac) { if (strlen(av[1]) != strspn(av[1],"0123456789")) return 0*fprintf(stderr,"use: %s [duration] dit in ms, default %d\n",*av,dit); dit = BIND(atoi(av[1]),1,1000); } sprintf(dah," -n -f 440 -l %d -D %d",3*dit,dit); sprintf(dih," -n -f 440 -l %d -D %d",dit,dit); sprintf(medium," -n -D %d",(3-1)*dit); sprintf(word," -n -D %d",(7-(3-1)-1)*dit); while (NULL != fgets(sin,72,stdin)) puts(translate(sin,sout)); return 0; }
Write the same algorithm in C# as shown in this Tcl implementation.
package require sound proc pause n { global t after [expr {$t * $n}] set ok 1 vwait ok } proc beep n { global frequency set f [snack::filter generator $frequency 30000 0.0 sine -1] set s [snack::sound -rate 22050] $s play -filter $f pause $n $s stop $s destroy $f destroy pause 1 } interp alias {} dit {} beep 1 interp alias {} dah {} beep 3 set MORSE_CODE { "!" "---." "\"" ".-..-." "$" "...-..-" "'" ".----." "(" "-.--." ")" "-.--.-" "+" ".-.-." "," "--..--" "-" "-....-" "." ".-.-.-" "/" "-..-." ":" "---..." ";" "-.-.-." "=" "-...-" "?" "..--.." "@" ".--.-." "[" "-.--." "]" "-.--.-" "_" "..--.-" "0" "-----" "1" ".----" "2" "..---" "3" "...--" "4" "....-" "5" "....." "6" "-...." "7" "--..." "8" "---.." "9" "----." "A" ".-" "B" "-..." "C" "-.-." "D" "-.." "E" "." "F" "..-." "G" "--." "H" "...." "I" ".." "J" ".---" "K" "-.-" "L" ".-.." "M" "--" "N" "-." "O" "---" "P" ".--." "Q" "--.-" "R" ".-." "S" "..." "T" "-" "U" "..-" "V" "...-" "W" ".--" "X" "-..-" "Y" "-.--" "Z" "--.." } proc morse {str wpm} { global t MORSE_CODE set t [expr {1200 / $wpm}] set map {"\\" {} " " {[pause 4]}} foreach {from to} $MORSE_CODE {lappend map $from "$to\[pause 3\]"} set s [string map $map [string toupper $str]] subst [string map {"." [dit] "-" [dah]} $s] return } set frequency 700 morse "Morse code with Tcl and Snack." 20
using System; using System.Collections.Generic; namespace Morse { class Morse { static void Main(string[] args) { string word = "sos"; Dictionary<string, string> Codes = new Dictionary<string, string> { {"a", ".- "}, {"b", "-... "}, {"c", "-.-. "}, {"d", "-.. "}, {"e", ". "}, {"f", "..-. "}, {"g", "--. "}, {"h", ".... "}, {"i", ".. "}, {"j", ".--- "}, {"k", "-.- "}, {"l", ".-.. "}, {"m", "-- "}, {"n", "-. "}, {"o", "--- "}, {"p", ".--. "}, {"q", "--.- "}, {"r", ".-. "}, {"s", "... "}, {"t", "- "}, {"u", "..- "}, {"v", "...- "}, {"w", ".-- "}, {"x", "-..- "}, {"y", "-.-- "}, {"z", "--.. "}, {"0", "-----"}, {"1", ".----"}, {"2", "..---"}, {"3", "...--"}, {"4", "....-"}, {"5", "....."}, {"6", "-...."}, {"7", "--..."}, {"8", "---.."}, {"9", "----."} }; foreach (char c in word.ToCharArray()) { string rslt = Codes[c.ToString()].Trim(); foreach (char c2 in rslt.ToCharArray()) { if (c2 == '.') Console.Beep(1000, 250); else Console.Beep(1000, 750); } System.Threading.Thread.Sleep(50); } } } }
Preserve the algorithm and functionality while converting the code from Tcl to Java.
package require sound proc pause n { global t after [expr {$t * $n}] set ok 1 vwait ok } proc beep n { global frequency set f [snack::filter generator $frequency 30000 0.0 sine -1] set s [snack::sound -rate 22050] $s play -filter $f pause $n $s stop $s destroy $f destroy pause 1 } interp alias {} dit {} beep 1 interp alias {} dah {} beep 3 set MORSE_CODE { "!" "---." "\"" ".-..-." "$" "...-..-" "'" ".----." "(" "-.--." ")" "-.--.-" "+" ".-.-." "," "--..--" "-" "-....-" "." ".-.-.-" "/" "-..-." ":" "---..." ";" "-.-.-." "=" "-...-" "?" "..--.." "@" ".--.-." "[" "-.--." "]" "-.--.-" "_" "..--.-" "0" "-----" "1" ".----" "2" "..---" "3" "...--" "4" "....-" "5" "....." "6" "-...." "7" "--..." "8" "---.." "9" "----." "A" ".-" "B" "-..." "C" "-.-." "D" "-.." "E" "." "F" "..-." "G" "--." "H" "...." "I" ".." "J" ".---" "K" "-.-" "L" ".-.." "M" "--" "N" "-." "O" "---" "P" ".--." "Q" "--.-" "R" ".-." "S" "..." "T" "-" "U" "..-" "V" "...-" "W" ".--" "X" "-..-" "Y" "-.--" "Z" "--.." } proc morse {str wpm} { global t MORSE_CODE set t [expr {1200 / $wpm}] set map {"\\" {} " " {[pause 4]}} foreach {from to} $MORSE_CODE {lappend map $from "$to\[pause 3\]"} set s [string map $map [string toupper $str]] subst [string map {"." [dit] "-" [dah]} $s] return } set frequency 700 morse "Morse code with Tcl and Snack." 20
import java.util.*; public class MorseCode { final static String[][] code = { {"A", ".- "}, {"B", "-... "}, {"C", "-.-. "}, {"D", "-.. "}, {"E", ". "}, {"F", "..-. "}, {"G", "--. "}, {"H", ".... "}, {"I", ".. "}, {"J", ".--- "}, {"K", "-.- "}, {"L", ".-.. "}, {"M", "-- "}, {"N", "-. "}, {"O", "--- "}, {"P", ".--. "}, {"Q", "--.- "}, {"R", ".-. "}, {"S", "... "}, {"T", "- "}, {"U", "..- "}, {"V", "...- "}, {"W", ".- - "}, {"X", "-..- "}, {"Y", "-.-- "}, {"Z", "--.. "}, {"0", "----- "}, {"1", ".---- "}, {"2", "..--- "}, {"3", "...-- "}, {"4", "....- "}, {"5", "..... "}, {"6", "-.... "}, {"7", "--... "}, {"8", "---.. "}, {"9", "----. "}, {"'", ".----. "}, {":", "---... "}, {",", "--..-- "}, {"-", "-....- "}, {"(", "-.--.- "}, {".", ".-.-.- "}, {"?", "..--.. "}, {";", "-.-.-. "}, {"/", "-..-. "}, {"-", "..--.- "}, {")", "---.. "}, {"=", "-...- "}, {"@", ".--.-. "}, {"\"", ".-..-."}, {"+", ".-.-. "}, {" ", "/"}}; final static Map<Character, String> map = new HashMap<>(); static { for (String[] pair : code) map.put(pair[0].charAt(0), pair[1].trim()); } public static void main(String[] args) { printMorse("sos"); printMorse(" Hello World!"); printMorse("Rosetta Code"); } static void printMorse(String input) { System.out.printf("%s %n", input); input = input.trim().replaceAll("[ ]+", " ").toUpperCase(); for (char c : input.toCharArray()) { String s = map.get(c); if (s != null) System.out.printf("%s ", s); } System.out.println("\n"); } }
Convert the following code from Tcl to Python, ensuring the logic remains intact.
package require sound proc pause n { global t after [expr {$t * $n}] set ok 1 vwait ok } proc beep n { global frequency set f [snack::filter generator $frequency 30000 0.0 sine -1] set s [snack::sound -rate 22050] $s play -filter $f pause $n $s stop $s destroy $f destroy pause 1 } interp alias {} dit {} beep 1 interp alias {} dah {} beep 3 set MORSE_CODE { "!" "---." "\"" ".-..-." "$" "...-..-" "'" ".----." "(" "-.--." ")" "-.--.-" "+" ".-.-." "," "--..--" "-" "-....-" "." ".-.-.-" "/" "-..-." ":" "---..." ";" "-.-.-." "=" "-...-" "?" "..--.." "@" ".--.-." "[" "-.--." "]" "-.--.-" "_" "..--.-" "0" "-----" "1" ".----" "2" "..---" "3" "...--" "4" "....-" "5" "....." "6" "-...." "7" "--..." "8" "---.." "9" "----." "A" ".-" "B" "-..." "C" "-.-." "D" "-.." "E" "." "F" "..-." "G" "--." "H" "...." "I" ".." "J" ".---" "K" "-.-" "L" ".-.." "M" "--" "N" "-." "O" "---" "P" ".--." "Q" "--.-" "R" ".-." "S" "..." "T" "-" "U" "..-" "V" "...-" "W" ".--" "X" "-..-" "Y" "-.--" "Z" "--.." } proc morse {str wpm} { global t MORSE_CODE set t [expr {1200 / $wpm}] set map {"\\" {} " " {[pause 4]}} foreach {from to} $MORSE_CODE {lappend map $from "$to\[pause 3\]"} set s [string map $map [string toupper $str]] subst [string map {"." [dit] "-" [dah]} $s] return } set frequency 700 morse "Morse code with Tcl and Snack." 20
import time, winsound char2morse = { "!": "---.", "\"": ".-..-.", "$": "...-..-", "'": ".----.", "(": "-.--.", ")": "-.--.-", "+": ".-.-.", ",": "--..--", "-": "-....-", ".": ".-.-.-", "/": "-..-.", "0": "-----", "1": ".----", "2": "..---", "3": "...--", "4": "....-", "5": ".....", "6": "-....", "7": "--...", "8": "---..", "9": "----.", ":": "---...", ";": "-.-.-.", "=": "-...-", "?": "..--..", "@": ".--.-.", "A": ".-", "B": "-...", "C": "-.-.", "D": "-..", "E": ".", "F": "..-.", "G": "--.", "H": "....", "I": "..", "J": ".---", "K": "-.-", "L": ".-..", "M": "--", "N": "-.", "O": "---", "P": ".--.", "Q": "--.-", "R": ".-.", "S": "...", "T": "-", "U": "..-", "V": "...-", "W": ".--", "X": "-..-", "Y": "-.--", "Z": "--..", "[": "-.--.", "]": "-.--.-", "_": "..--.-", } e = 50 f = 1280 chargap = 1 wordgap = 7 def gap(n=1): time.sleep(n * e / 1000) off = gap def on(n=1): winsound.Beep(f, n * e) def dit(): on(); off() def dah(): on(3); off() def bloop(n=3): winsound.Beep(f//2, n * e) def windowsmorse(text): for word in text.strip().upper().split(): for char in word: for element in char2morse.get(char, '?'): if element == '-': dah() elif element == '.': dit() else: bloop() gap(chargap) gap(wordgap) while True: windowsmorse(input('A string to change into morse: '))
Write a version of this Tcl function in VB with identical behavior.
package require sound proc pause n { global t after [expr {$t * $n}] set ok 1 vwait ok } proc beep n { global frequency set f [snack::filter generator $frequency 30000 0.0 sine -1] set s [snack::sound -rate 22050] $s play -filter $f pause $n $s stop $s destroy $f destroy pause 1 } interp alias {} dit {} beep 1 interp alias {} dah {} beep 3 set MORSE_CODE { "!" "---." "\"" ".-..-." "$" "...-..-" "'" ".----." "(" "-.--." ")" "-.--.-" "+" ".-.-." "," "--..--" "-" "-....-" "." ".-.-.-" "/" "-..-." ":" "---..." ";" "-.-.-." "=" "-...-" "?" "..--.." "@" ".--.-." "[" "-.--." "]" "-.--.-" "_" "..--.-" "0" "-----" "1" ".----" "2" "..---" "3" "...--" "4" "....-" "5" "....." "6" "-...." "7" "--..." "8" "---.." "9" "----." "A" ".-" "B" "-..." "C" "-.-." "D" "-.." "E" "." "F" "..-." "G" "--." "H" "...." "I" ".." "J" ".---" "K" "-.-" "L" ".-.." "M" "--" "N" "-." "O" "---" "P" ".--." "Q" "--.-" "R" ".-." "S" "..." "T" "-" "U" "..-" "V" "...-" "W" ".--" "X" "-..-" "Y" "-.--" "Z" "--.." } proc morse {str wpm} { global t MORSE_CODE set t [expr {1200 / $wpm}] set map {"\\" {} " " {[pause 4]}} foreach {from to} $MORSE_CODE {lappend map $from "$to\[pause 3\]"} set s [string map $map [string toupper $str]] subst [string map {"." [dit] "-" [dah]} $s] return } set frequency 700 morse "Morse code with Tcl and Snack." 20
Option Explicit Private Declare Function Beep Lib "kernel32" (ByVal dwFreq As Long, ByVal dwDuration As Long) As Long Private Declare Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As Long) Private Const MORSE_ALPHA As String = ".-,-...,-.-.,-..,.,..-.,--.,....,..,.---,-.-,.-..,--,-.,---,.--.,--.-,.-.,...,-,..-,...-,.--,-..-,-.--,--.." Private Const MORSE_NUMERIC As String = "-----,.----,..---,...--,....-,.....,-....,--...,---..,----." Private Const ONE_UNIT As Integer = 100 Private Const BEEP_DOT As Integer = ONE_UNIT Private Const BEEP_DASH As Integer = 3 * ONE_UNIT Private Const BEEP_OTHER As Integer = 7 * ONE_UNIT Private Const DELAY As Integer = ONE_UNIT Private Const LETTERS_DELAY As Integer = 3 * ONE_UNIT Private Const SPACE_DELAY As Integer = 7 * ONE_UNIT Private Const FREQUENCY_CHARS As Integer = 1200 Private Const FREQUENCY_OTHERCHARS As Integer = 400 Sub Main() Dim p$, temp$ p = ToMorse("Hel/lo 123 world") temp = Replace(p, "+", "") Debug.Print Replace(temp, "_", "") PlayMorse p End Sub Private Function ToMorse(s As String) As String Dim i&, t$, j& s = UCase(s) For i = 1 To Len(s) j = Asc(Mid(s, i, 1)) Select Case j Case 65 To 90 t = t & Split(MORSE_ALPHA, ",")(j - 65) & "+" Case 48 To 57 t = t & Split(MORSE_NUMERIC, ",")(j - 48) & "+" Case 32 t = t & " " & "+" Case Else t = t & "_" & "+" End Select Next i ToMorse = t End Function Private Sub PlayMorse(s As String) Dim i& For i = 1 To Len(s) Select Case Mid(s, i, 1) Case ".": Beep FREQUENCY_CHARS, BEEP_DOT Case "-": Beep FREQUENCY_CHARS, BEEP_DASH Case "_": Beep FREQUENCY_OTHERCHARS, BEEP_OTHER Case "+": Sleep LETTERS_DELAY Case " ": Sleep SPACE_DELAY End Select Sleep DELAY Next i End Sub
Ensure the translated Go code behaves exactly like the original Tcl snippet.
package require sound proc pause n { global t after [expr {$t * $n}] set ok 1 vwait ok } proc beep n { global frequency set f [snack::filter generator $frequency 30000 0.0 sine -1] set s [snack::sound -rate 22050] $s play -filter $f pause $n $s stop $s destroy $f destroy pause 1 } interp alias {} dit {} beep 1 interp alias {} dah {} beep 3 set MORSE_CODE { "!" "---." "\"" ".-..-." "$" "...-..-" "'" ".----." "(" "-.--." ")" "-.--.-" "+" ".-.-." "," "--..--" "-" "-....-" "." ".-.-.-" "/" "-..-." ":" "---..." ";" "-.-.-." "=" "-...-" "?" "..--.." "@" ".--.-." "[" "-.--." "]" "-.--.-" "_" "..--.-" "0" "-----" "1" ".----" "2" "..---" "3" "...--" "4" "....-" "5" "....." "6" "-...." "7" "--..." "8" "---.." "9" "----." "A" ".-" "B" "-..." "C" "-.-." "D" "-.." "E" "." "F" "..-." "G" "--." "H" "...." "I" ".." "J" ".---" "K" "-.-" "L" ".-.." "M" "--" "N" "-." "O" "---" "P" ".--." "Q" "--.-" "R" ".-." "S" "..." "T" "-" "U" "..-" "V" "...-" "W" ".--" "X" "-..-" "Y" "-.--" "Z" "--.." } proc morse {str wpm} { global t MORSE_CODE set t [expr {1200 / $wpm}] set map {"\\" {} " " {[pause 4]}} foreach {from to} $MORSE_CODE {lappend map $from "$to\[pause 3\]"} set s [string map $map [string toupper $str]] subst [string map {"." [dit] "-" [dah]} $s] return } set frequency 700 morse "Morse code with Tcl and Snack." 20
package main import ( "flag" "fmt" "log" "regexp" "strings" "syscall" "time" "unicode" ) type key struct { duration int on bool sym string } var ( runeToKeys = map[rune][]key{} interCharGap = []key{{1, false, ""}} punctGap = []key{{7, false, " / "}} charGap = []key{{3, false, " "}} wordGap = []key{{7, false, " / "}} ) const rawMorse = ` A:.- J:.--- S:... 1:.---- .:.-.-.-  ::---... B:-... K:-.- T:- 2:..--- ,:--..--  ;:-.-.-. C:-.-. L:.-.. U:..- 3:...--  ?:..--.. =:-...- D:-.. M:-- V:...- 4:....- ':.----. +:.-.-. E:. N:-. W:.-- 5:.....  !:-.-.-- -:-....- F:..-. O:--- X:-..- 6:-.... /:-..-. _:..--.- G:--. P:.--. Y:-.-- 7:--... (:-.--. ":.-..-. H:.... Q:--.- Z:--.. 8:---.. ):-.--.- $:...-..- I:.. R:.-. 0:----- 9:----. &:.-... @:.--.-. ` func init() { r := regexp.MustCompile("([^ ]):([.-]+)") for _, m := range r.FindAllStringSubmatch(rawMorse, -1) { c := m[1][0] keys := []key{} for i, dd := range m[2] { if i > 0 { keys = append(keys, interCharGap...) } if dd == '.' { keys = append(keys, key{1, true, "."}) } else if dd == '-' { keys = append(keys, key{3, true, "-"}) } else { log.Fatalf("found %c in morse for %c", dd, c) } runeToKeys[rune(c)] = keys runeToKeys[unicode.ToLower(rune(c))] = keys } } } func MorseKeys(in string) ([]key, error) { afterWord := false afterChar := false result := []key{} for _, c := range in { if unicode.IsSpace(c) { afterWord = true continue } morse, ok := runeToKeys[c] if !ok { return nil, fmt.Errorf("can't translate %c to morse", c) } if unicode.IsPunct(c) && afterChar { result = append(result, punctGap...) } else if afterWord { result = append(result, wordGap...) } else if afterChar { result = append(result, charGap...) } result = append(result, morse...) afterChar = true afterWord = false } return result, nil } func main() { var ditDuration time.Duration flag.DurationVar(&ditDuration, "d", 40*time.Millisecond, "length of dit") flag.Parse() in := "hello world." if len(flag.Args()) > 1 { in = strings.Join(flag.Args(), " ") } keys, err := MorseKeys(in) if err != nil { log.Fatalf("failed to translate: %s", err) } for _, k := range keys { if k.on { if err := note(true); err != nil { log.Fatalf("failed to play note: %s", err) } } fmt.Print(k.sym) time.Sleep(ditDuration * time.Duration(k.duration)) if k.on { if err := note(false); err != nil { log.Fatalf("failed to stop note: %s", err) } } } fmt.Println() } var consoleFD uintptr func init() { fd, err := syscall.Open("/dev/console", syscall.O_WRONLY, 0) if err != nil { log.Fatalf("failed to get console device: %s", err) } consoleFD = uintptr(fd) } const KIOCSOUND = 0x4B2F const clockTickRate = 1193180 const freqHz = 600 func note(on bool) error { arg := uintptr(0) if on { arg = clockTickRate / freqHz } _, _, errno := syscall.Syscall(syscall.SYS_IOCTL, consoleFD, KIOCSOUND, arg) if errno != 0 { return errno } return nil }
Change the following C code into Rust without altering its purpose.
#include <ctype.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #define BIND(A,L,H) ((L)<(A)?(A)<(H)?(A):(H):(L)) char dih[50],dah[50],medium[30],word[30], *dd[2] = {dih,dah}; const char *ascii = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789.,?'!/()&:;=+-_\"$@", *itu[] = { "13","3111","3131","311","1","1131","331","1111","11","1333","313","1311","33","31","333","1331","3313","131","111","3","113","1113","133","3113","3133","3311","33333","13333","11333","11133","11113","11111","31111","33111","33311","33331","131313","331133","113311","133331","313133","31131","31331","313313","13111","333111","313131","31113","13131","311113","113313","131131","1113113","133131" }; void append(char*s,const char*morse) { for (; *morse; ++morse) strcat(s,dd['3'==*morse]); strcat(s,medium); } char*translate(const char*i,char*o) { const char*pc; sprintf(o,"beep"); for (; *i; ++i) if (NULL == (pc = strchr(ascii,toupper(*i)))) strcat(o,word); else append(o,itu[pc-ascii]); strcat(o,word); return o; } int main(int ac,char*av[]) { char sin[73],sout[100000]; int dit = 100; if (1 < ac) { if (strlen(av[1]) != strspn(av[1],"0123456789")) return 0*fprintf(stderr,"use: %s [duration] dit in ms, default %d\n",*av,dit); dit = BIND(atoi(av[1]),1,1000); } sprintf(dah," -n -f 440 -l %d -D %d",3*dit,dit); sprintf(dih," -n -f 440 -l %d -D %d",dit,dit); sprintf(medium," -n -D %d",(3-1)*dit); sprintf(word," -n -D %d",(7-(3-1)-1)*dit); while (NULL != fgets(sin,72,stdin)) puts(translate(sin,sout)); return 0; }
use std::process; use structopt::StructOpt; use morse_code::{Config, Opt, run}; fn main() { let opts = Opt::from_args(); let mut config = Config::new(opts).unwrap_or_else(|err| { eprintln!("Problem parsing arguments: {}", err); process::exit(1); }); if let Err(err) = run(&mut config) { eprintln!("Application error: {}", err); process::exit(2); } }
Can you help me rewrite this code in Rust instead of Go, keeping it the same logically?
package main import ( "flag" "fmt" "log" "regexp" "strings" "syscall" "time" "unicode" ) type key struct { duration int on bool sym string } var ( runeToKeys = map[rune][]key{} interCharGap = []key{{1, false, ""}} punctGap = []key{{7, false, " / "}} charGap = []key{{3, false, " "}} wordGap = []key{{7, false, " / "}} ) const rawMorse = ` A:.- J:.--- S:... 1:.---- .:.-.-.-  ::---... B:-... K:-.- T:- 2:..--- ,:--..--  ;:-.-.-. C:-.-. L:.-.. U:..- 3:...--  ?:..--.. =:-...- D:-.. M:-- V:...- 4:....- ':.----. +:.-.-. E:. N:-. W:.-- 5:.....  !:-.-.-- -:-....- F:..-. O:--- X:-..- 6:-.... /:-..-. _:..--.- G:--. P:.--. Y:-.-- 7:--... (:-.--. ":.-..-. H:.... Q:--.- Z:--.. 8:---.. ):-.--.- $:...-..- I:.. R:.-. 0:----- 9:----. &:.-... @:.--.-. ` func init() { r := regexp.MustCompile("([^ ]):([.-]+)") for _, m := range r.FindAllStringSubmatch(rawMorse, -1) { c := m[1][0] keys := []key{} for i, dd := range m[2] { if i > 0 { keys = append(keys, interCharGap...) } if dd == '.' { keys = append(keys, key{1, true, "."}) } else if dd == '-' { keys = append(keys, key{3, true, "-"}) } else { log.Fatalf("found %c in morse for %c", dd, c) } runeToKeys[rune(c)] = keys runeToKeys[unicode.ToLower(rune(c))] = keys } } } func MorseKeys(in string) ([]key, error) { afterWord := false afterChar := false result := []key{} for _, c := range in { if unicode.IsSpace(c) { afterWord = true continue } morse, ok := runeToKeys[c] if !ok { return nil, fmt.Errorf("can't translate %c to morse", c) } if unicode.IsPunct(c) && afterChar { result = append(result, punctGap...) } else if afterWord { result = append(result, wordGap...) } else if afterChar { result = append(result, charGap...) } result = append(result, morse...) afterChar = true afterWord = false } return result, nil } func main() { var ditDuration time.Duration flag.DurationVar(&ditDuration, "d", 40*time.Millisecond, "length of dit") flag.Parse() in := "hello world." if len(flag.Args()) > 1 { in = strings.Join(flag.Args(), " ") } keys, err := MorseKeys(in) if err != nil { log.Fatalf("failed to translate: %s", err) } for _, k := range keys { if k.on { if err := note(true); err != nil { log.Fatalf("failed to play note: %s", err) } } fmt.Print(k.sym) time.Sleep(ditDuration * time.Duration(k.duration)) if k.on { if err := note(false); err != nil { log.Fatalf("failed to stop note: %s", err) } } } fmt.Println() } var consoleFD uintptr func init() { fd, err := syscall.Open("/dev/console", syscall.O_WRONLY, 0) if err != nil { log.Fatalf("failed to get console device: %s", err) } consoleFD = uintptr(fd) } const KIOCSOUND = 0x4B2F const clockTickRate = 1193180 const freqHz = 600 func note(on bool) error { arg := uintptr(0) if on { arg = clockTickRate / freqHz } _, _, errno := syscall.Syscall(syscall.SYS_IOCTL, consoleFD, KIOCSOUND, arg) if errno != 0 { return errno } return nil }
use std::process; use structopt::StructOpt; use morse_code::{Config, Opt, run}; fn main() { let opts = Opt::from_args(); let mut config = Config::new(opts).unwrap_or_else(|err| { eprintln!("Problem parsing arguments: {}", err); process::exit(1); }); if let Err(err) = run(&mut config) { eprintln!("Application error: {}", err); process::exit(2); } }
Can you help me rewrite this code in Python instead of Rust, keeping it the same logically?
use std::process; use structopt::StructOpt; use morse_code::{Config, Opt, run}; fn main() { let opts = Opt::from_args(); let mut config = Config::new(opts).unwrap_or_else(|err| { eprintln!("Problem parsing arguments: {}", err); process::exit(1); }); if let Err(err) = run(&mut config) { eprintln!("Application error: {}", err); process::exit(2); } }
import time, winsound char2morse = { "!": "---.", "\"": ".-..-.", "$": "...-..-", "'": ".----.", "(": "-.--.", ")": "-.--.-", "+": ".-.-.", ",": "--..--", "-": "-....-", ".": ".-.-.-", "/": "-..-.", "0": "-----", "1": ".----", "2": "..---", "3": "...--", "4": "....-", "5": ".....", "6": "-....", "7": "--...", "8": "---..", "9": "----.", ":": "---...", ";": "-.-.-.", "=": "-...-", "?": "..--..", "@": ".--.-.", "A": ".-", "B": "-...", "C": "-.-.", "D": "-..", "E": ".", "F": "..-.", "G": "--.", "H": "....", "I": "..", "J": ".---", "K": "-.-", "L": ".-..", "M": "--", "N": "-.", "O": "---", "P": ".--.", "Q": "--.-", "R": ".-.", "S": "...", "T": "-", "U": "..-", "V": "...-", "W": ".--", "X": "-..-", "Y": "-.--", "Z": "--..", "[": "-.--.", "]": "-.--.-", "_": "..--.-", } e = 50 f = 1280 chargap = 1 wordgap = 7 def gap(n=1): time.sleep(n * e / 1000) off = gap def on(n=1): winsound.Beep(f, n * e) def dit(): on(); off() def dah(): on(3); off() def bloop(n=3): winsound.Beep(f//2, n * e) def windowsmorse(text): for word in text.strip().upper().split(): for char in word: for element in char2morse.get(char, '?'): if element == '-': dah() elif element == '.': dit() else: bloop() gap(chargap) gap(wordgap) while True: windowsmorse(input('A string to change into morse: '))
Translate this program into VB but keep the logic exactly as in Rust.
use std::process; use structopt::StructOpt; use morse_code::{Config, Opt, run}; fn main() { let opts = Opt::from_args(); let mut config = Config::new(opts).unwrap_or_else(|err| { eprintln!("Problem parsing arguments: {}", err); process::exit(1); }); if let Err(err) = run(&mut config) { eprintln!("Application error: {}", err); process::exit(2); } }
Option Explicit Private Declare Function Beep Lib "kernel32" (ByVal dwFreq As Long, ByVal dwDuration As Long) As Long Private Declare Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As Long) Private Const MORSE_ALPHA As String = ".-,-...,-.-.,-..,.,..-.,--.,....,..,.---,-.-,.-..,--,-.,---,.--.,--.-,.-.,...,-,..-,...-,.--,-..-,-.--,--.." Private Const MORSE_NUMERIC As String = "-----,.----,..---,...--,....-,.....,-....,--...,---..,----." Private Const ONE_UNIT As Integer = 100 Private Const BEEP_DOT As Integer = ONE_UNIT Private Const BEEP_DASH As Integer = 3 * ONE_UNIT Private Const BEEP_OTHER As Integer = 7 * ONE_UNIT Private Const DELAY As Integer = ONE_UNIT Private Const LETTERS_DELAY As Integer = 3 * ONE_UNIT Private Const SPACE_DELAY As Integer = 7 * ONE_UNIT Private Const FREQUENCY_CHARS As Integer = 1200 Private Const FREQUENCY_OTHERCHARS As Integer = 400 Sub Main() Dim p$, temp$ p = ToMorse("Hel/lo 123 world") temp = Replace(p, "+", "") Debug.Print Replace(temp, "_", "") PlayMorse p End Sub Private Function ToMorse(s As String) As String Dim i&, t$, j& s = UCase(s) For i = 1 To Len(s) j = Asc(Mid(s, i, 1)) Select Case j Case 65 To 90 t = t & Split(MORSE_ALPHA, ",")(j - 65) & "+" Case 48 To 57 t = t & Split(MORSE_NUMERIC, ",")(j - 48) & "+" Case 32 t = t & " " & "+" Case Else t = t & "_" & "+" End Select Next i ToMorse = t End Function Private Sub PlayMorse(s As String) Dim i& For i = 1 To Len(s) Select Case Mid(s, i, 1) Case ".": Beep FREQUENCY_CHARS, BEEP_DOT Case "-": Beep FREQUENCY_CHARS, BEEP_DASH Case "_": Beep FREQUENCY_OTHERCHARS, BEEP_OTHER Case "+": Sleep LETTERS_DELAY Case " ": Sleep SPACE_DELAY End Select Sleep DELAY Next i End Sub
Write a version of this C# function in Rust with identical behavior.
using System; using System.Collections.Generic; namespace Morse { class Morse { static void Main(string[] args) { string word = "sos"; Dictionary<string, string> Codes = new Dictionary<string, string> { {"a", ".- "}, {"b", "-... "}, {"c", "-.-. "}, {"d", "-.. "}, {"e", ". "}, {"f", "..-. "}, {"g", "--. "}, {"h", ".... "}, {"i", ".. "}, {"j", ".--- "}, {"k", "-.- "}, {"l", ".-.. "}, {"m", "-- "}, {"n", "-. "}, {"o", "--- "}, {"p", ".--. "}, {"q", "--.- "}, {"r", ".-. "}, {"s", "... "}, {"t", "- "}, {"u", "..- "}, {"v", "...- "}, {"w", ".-- "}, {"x", "-..- "}, {"y", "-.-- "}, {"z", "--.. "}, {"0", "-----"}, {"1", ".----"}, {"2", "..---"}, {"3", "...--"}, {"4", "....-"}, {"5", "....."}, {"6", "-...."}, {"7", "--..."}, {"8", "---.."}, {"9", "----."} }; foreach (char c in word.ToCharArray()) { string rslt = Codes[c.ToString()].Trim(); foreach (char c2 in rslt.ToCharArray()) { if (c2 == '.') Console.Beep(1000, 250); else Console.Beep(1000, 750); } System.Threading.Thread.Sleep(50); } } } }
use std::process; use structopt::StructOpt; use morse_code::{Config, Opt, run}; fn main() { let opts = Opt::from_args(); let mut config = Config::new(opts).unwrap_or_else(|err| { eprintln!("Problem parsing arguments: {}", err); process::exit(1); }); if let Err(err) = run(&mut config) { eprintln!("Application error: {}", err); process::exit(2); } }
Port the provided Java code into Rust while preserving the original functionality.
import java.util.*; public class MorseCode { final static String[][] code = { {"A", ".- "}, {"B", "-... "}, {"C", "-.-. "}, {"D", "-.. "}, {"E", ". "}, {"F", "..-. "}, {"G", "--. "}, {"H", ".... "}, {"I", ".. "}, {"J", ".--- "}, {"K", "-.- "}, {"L", ".-.. "}, {"M", "-- "}, {"N", "-. "}, {"O", "--- "}, {"P", ".--. "}, {"Q", "--.- "}, {"R", ".-. "}, {"S", "... "}, {"T", "- "}, {"U", "..- "}, {"V", "...- "}, {"W", ".- - "}, {"X", "-..- "}, {"Y", "-.-- "}, {"Z", "--.. "}, {"0", "----- "}, {"1", ".---- "}, {"2", "..--- "}, {"3", "...-- "}, {"4", "....- "}, {"5", "..... "}, {"6", "-.... "}, {"7", "--... "}, {"8", "---.. "}, {"9", "----. "}, {"'", ".----. "}, {":", "---... "}, {",", "--..-- "}, {"-", "-....- "}, {"(", "-.--.- "}, {".", ".-.-.- "}, {"?", "..--.. "}, {";", "-.-.-. "}, {"/", "-..-. "}, {"-", "..--.- "}, {")", "---.. "}, {"=", "-...- "}, {"@", ".--.-. "}, {"\"", ".-..-."}, {"+", ".-.-. "}, {" ", "/"}}; final static Map<Character, String> map = new HashMap<>(); static { for (String[] pair : code) map.put(pair[0].charAt(0), pair[1].trim()); } public static void main(String[] args) { printMorse("sos"); printMorse(" Hello World!"); printMorse("Rosetta Code"); } static void printMorse(String input) { System.out.printf("%s %n", input); input = input.trim().replaceAll("[ ]+", " ").toUpperCase(); for (char c : input.toCharArray()) { String s = map.get(c); if (s != null) System.out.printf("%s ", s); } System.out.println("\n"); } }
use std::process; use structopt::StructOpt; use morse_code::{Config, Opt, run}; fn main() { let opts = Opt::from_args(); let mut config = Config::new(opts).unwrap_or_else(|err| { eprintln!("Problem parsing arguments: {}", err); process::exit(1); }); if let Err(err) = run(&mut config) { eprintln!("Application error: {}", err); process::exit(2); } }
Write the same algorithm in C# as shown in this Ada implementation.
with Ada.Containers.Indefinite_Ordered_Maps; with Ada.Containers.Ordered_Maps; with Ada.Finalization; generic type Symbol_Type is private; with function "<" (Left, Right : Symbol_Type) return Boolean is <>; with procedure Put (Item : Symbol_Type); type Symbol_Sequence is array (Positive range <>) of Symbol_Type; type Frequency_Type is private; with function "+" (Left, Right : Frequency_Type) return Frequency_Type is <>; with function "<" (Left, Right : Frequency_Type) return Boolean is <>; package Huffman is type Bit_Sequence is array (Positive range <>) of Boolean; Zero_Sequence : constant Bit_Sequence (1 .. 0) := (others => False); procedure Put (Code : Bit_Sequence); package Frequency_Maps is new Ada.Containers.Ordered_Maps (Element_Type => Frequency_Type, Key_Type => Symbol_Type); type Huffman_Tree is private; procedure Create_Tree (Tree : out Huffman_Tree; Frequencies : Frequency_Maps.Map); function Encode (Tree : Huffman_Tree; Symbol : Symbol_Type) return Bit_Sequence; function Encode (Tree : Huffman_Tree; Symbols : Symbol_Sequence) return Bit_Sequence; function Decode (Tree : Huffman_Tree; Code : Bit_Sequence) return Symbol_Sequence; procedure Dump_Encoding (Tree : Huffman_Tree); private package Encoding_Maps is new Ada.Containers.Indefinite_Ordered_Maps (Element_Type => Bit_Sequence, Key_Type => Symbol_Type); type Huffman_Node; type Node_Access is access Huffman_Node; type Huffman_Node is record Frequency : Frequency_Type; Left_Child : Node_Access := null; Right_Child : Node_Access := null; Symbol : Symbol_Type; end record; function Create_Node (Symbol : Symbol_Type; Frequency : Frequency_Type) return Node_Access; function Create_Node (Left, Right : Node_Access) return Node_Access; procedure Fill (The_Node : Node_Access; Map : in out Encoding_Maps.Map; Prefix : Bit_Sequence); type Huffman_Tree is new Ada.Finalization.Controlled with record Tree : Node_Access := null; Map : Encoding_Maps.Map := Encoding_Maps.Empty_Map; end record; overriding procedure Finalize (Object : in out Huffman_Tree); end Huffman;
using System; using System.Collections.Generic; namespace Huffman_Encoding { public class PriorityQueue<T> where T : IComparable { protected List<T> LstHeap = new List<T>(); public virtual int Count { get { return LstHeap.Count; } } public virtual void Add(T val) { LstHeap.Add(val); SetAt(LstHeap.Count - 1, val); UpHeap(LstHeap.Count - 1); } public virtual T Peek() { if (LstHeap.Count == 0) { throw new IndexOutOfRangeException("Peeking at an empty priority queue"); } return LstHeap[0]; } public virtual T Pop() { if (LstHeap.Count == 0) { throw new IndexOutOfRangeException("Popping an empty priority queue"); } T valRet = LstHeap[0]; SetAt(0, LstHeap[LstHeap.Count - 1]); LstHeap.RemoveAt(LstHeap.Count - 1); DownHeap(0); return valRet; } protected virtual void SetAt(int i, T val) { LstHeap[i] = val; } protected bool RightSonExists(int i) { return RightChildIndex(i) < LstHeap.Count; } protected bool LeftSonExists(int i) { return LeftChildIndex(i) < LstHeap.Count; } protected int ParentIndex(int i) { return (i - 1) / 2; } protected int LeftChildIndex(int i) { return 2 * i + 1; } protected int RightChildIndex(int i) { return 2 * (i + 1); } protected T ArrayVal(int i) { return LstHeap[i]; } protected T Parent(int i) { return LstHeap[ParentIndex(i)]; } protected T Left(int i) { return LstHeap[LeftChildIndex(i)]; } protected T Right(int i) { return LstHeap[RightChildIndex(i)]; } protected void Swap(int i, int j) { T valHold = ArrayVal(i); SetAt(i, LstHeap[j]); SetAt(j, valHold); } protected void UpHeap(int i) { while (i > 0 && ArrayVal(i).CompareTo(Parent(i)) > 0) { Swap(i, ParentIndex(i)); i = ParentIndex(i); } } protected void DownHeap(int i) { while (i >= 0) { int iContinue = -1; if (RightSonExists(i) && Right(i).CompareTo(ArrayVal(i)) > 0) { iContinue = Left(i).CompareTo(Right(i)) < 0 ? RightChildIndex(i) : LeftChildIndex(i); } else if (LeftSonExists(i) && Left(i).CompareTo(ArrayVal(i)) > 0) { iContinue = LeftChildIndex(i); } if (iContinue >= 0 && iContinue < LstHeap.Count) { Swap(i, iContinue); } i = iContinue; } } } internal class HuffmanNode<T> : IComparable { internal HuffmanNode(double probability, T value) { Probability = probability; LeftSon = RightSon = Parent = null; Value = value; IsLeaf = true; } internal HuffmanNode(HuffmanNode<T> leftSon, HuffmanNode<T> rightSon) { LeftSon = leftSon; RightSon = rightSon; Probability = leftSon.Probability + rightSon.Probability; leftSon.IsZero = true; rightSon.IsZero = false; leftSon.Parent = rightSon.Parent = this; IsLeaf = false; } internal HuffmanNode<T> LeftSon { get; set; } internal HuffmanNode<T> RightSon { get; set; } internal HuffmanNode<T> Parent { get; set; } internal T Value { get; set; } internal bool IsLeaf { get; set; } internal bool IsZero { get; set; } internal int Bit { get { return IsZero ? 0 : 1; } } internal bool IsRoot { get { return Parent == null; } } internal double Probability { get; set; } public int CompareTo(object obj) { return -Probability.CompareTo(((HuffmanNode<T>) obj).Probability); } } public class Huffman<T> where T : IComparable { private readonly Dictionary<T, HuffmanNode<T>> _leafDictionary = new Dictionary<T, HuffmanNode<T>>(); private readonly HuffmanNode<T> _root; public Huffman(IEnumerable<T> values) { var counts = new Dictionary<T, int>(); var priorityQueue = new PriorityQueue<HuffmanNode<T>>(); int valueCount = 0; foreach (T value in values) { if (!counts.ContainsKey(value)) { counts[value] = 0; } counts[value]++; valueCount++; } foreach (T value in counts.Keys) { var node = new HuffmanNode<T>((double) counts[value] / valueCount, value); priorityQueue.Add(node); _leafDictionary[value] = node; } while (priorityQueue.Count > 1) { HuffmanNode<T> leftSon = priorityQueue.Pop(); HuffmanNode<T> rightSon = priorityQueue.Pop(); var parent = new HuffmanNode<T>(leftSon, rightSon); priorityQueue.Add(parent); } _root = priorityQueue.Pop(); _root.IsZero = false; } public List<int> Encode(T value) { var returnValue = new List<int>(); Encode(value, returnValue); return returnValue; } public void Encode(T value, List<int> encoding) { if (!_leafDictionary.ContainsKey(value)) { throw new ArgumentException("Invalid value in Encode"); } HuffmanNode<T> nodeCur = _leafDictionary[value]; var reverseEncoding = new List<int>(); while (!nodeCur.IsRoot) { reverseEncoding.Add(nodeCur.Bit); nodeCur = nodeCur.Parent; } reverseEncoding.Reverse(); encoding.AddRange(reverseEncoding); } public List<int> Encode(IEnumerable<T> values) { var returnValue = new List<int>(); foreach (T value in values) { Encode(value, returnValue); } return returnValue; } public T Decode(List<int> bitString, ref int position) { HuffmanNode<T> nodeCur = _root; while (!nodeCur.IsLeaf) { if (position > bitString.Count) { throw new ArgumentException("Invalid bitstring in Decode"); } nodeCur = bitString[position++] == 0 ? nodeCur.LeftSon : nodeCur.RightSon; } return nodeCur.Value; } public List<T> Decode(List<int> bitString) { int position = 0; var returnValue = new List<T>(); while (position != bitString.Count) { returnValue.Add(Decode(bitString, ref position)); } return returnValue; } } internal class Program { private const string Example = "this is an example for huffman encoding"; private static void Main() { var huffman = new Huffman<char>(Example); List<int> encoding = huffman.Encode(Example); List<char> decoding = huffman.Decode(encoding); var outString = new string(decoding.ToArray()); Console.WriteLine(outString == Example ? "Encoding/decoding worked" : "Encoding/Decoding failed"); var chars = new HashSet<char>(Example); foreach (char c in chars) { encoding = huffman.Encode(c); Console.Write("{0}: ", c); foreach (int bit in encoding) { Console.Write("{0}", bit); } Console.WriteLine(); } Console.ReadKey(); } } }
Please provide an equivalent version of this Ada code in C.
with Ada.Containers.Indefinite_Ordered_Maps; with Ada.Containers.Ordered_Maps; with Ada.Finalization; generic type Symbol_Type is private; with function "<" (Left, Right : Symbol_Type) return Boolean is <>; with procedure Put (Item : Symbol_Type); type Symbol_Sequence is array (Positive range <>) of Symbol_Type; type Frequency_Type is private; with function "+" (Left, Right : Frequency_Type) return Frequency_Type is <>; with function "<" (Left, Right : Frequency_Type) return Boolean is <>; package Huffman is type Bit_Sequence is array (Positive range <>) of Boolean; Zero_Sequence : constant Bit_Sequence (1 .. 0) := (others => False); procedure Put (Code : Bit_Sequence); package Frequency_Maps is new Ada.Containers.Ordered_Maps (Element_Type => Frequency_Type, Key_Type => Symbol_Type); type Huffman_Tree is private; procedure Create_Tree (Tree : out Huffman_Tree; Frequencies : Frequency_Maps.Map); function Encode (Tree : Huffman_Tree; Symbol : Symbol_Type) return Bit_Sequence; function Encode (Tree : Huffman_Tree; Symbols : Symbol_Sequence) return Bit_Sequence; function Decode (Tree : Huffman_Tree; Code : Bit_Sequence) return Symbol_Sequence; procedure Dump_Encoding (Tree : Huffman_Tree); private package Encoding_Maps is new Ada.Containers.Indefinite_Ordered_Maps (Element_Type => Bit_Sequence, Key_Type => Symbol_Type); type Huffman_Node; type Node_Access is access Huffman_Node; type Huffman_Node is record Frequency : Frequency_Type; Left_Child : Node_Access := null; Right_Child : Node_Access := null; Symbol : Symbol_Type; end record; function Create_Node (Symbol : Symbol_Type; Frequency : Frequency_Type) return Node_Access; function Create_Node (Left, Right : Node_Access) return Node_Access; procedure Fill (The_Node : Node_Access; Map : in out Encoding_Maps.Map; Prefix : Bit_Sequence); type Huffman_Tree is new Ada.Finalization.Controlled with record Tree : Node_Access := null; Map : Encoding_Maps.Map := Encoding_Maps.Empty_Map; end record; overriding procedure Finalize (Object : in out Huffman_Tree); end Huffman;
#include <stdio.h> #include <stdlib.h> #include <string.h> #define BYTES 256 struct huffcode { int nbits; int code; }; typedef struct huffcode huffcode_t; struct huffheap { int *h; int n, s, cs; long *f; }; typedef struct huffheap heap_t; static heap_t *_heap_create(int s, long *f) { heap_t *h; h = malloc(sizeof(heap_t)); h->h = malloc(sizeof(int)*s); h->s = h->cs = s; h->n = 0; h->f = f; return h; } static void _heap_destroy(heap_t *heap) { free(heap->h); free(heap); } #define swap_(I,J) do { int t_; t_ = a[(I)]; \ a[(I)] = a[(J)]; a[(J)] = t_; } while(0) static void _heap_sort(heap_t *heap) { int i=1, j=2; int *a = heap->h; while(i < heap->n) { if ( heap->f[a[i-1]] >= heap->f[a[i]] ) { i = j; j++; } else { swap_(i-1, i); i--; i = (i==0) ? j++ : i; } } } #undef swap_ static void _heap_add(heap_t *heap, int c) { if ( (heap->n + 1) > heap->s ) { heap->h = realloc(heap->h, heap->s + heap->cs); heap->s += heap->cs; } heap->h[heap->n] = c; heap->n++; _heap_sort(heap); } static int _heap_remove(heap_t *heap) { if ( heap->n > 0 ) { heap->n--; return heap->h[heap->n]; } return -1; } huffcode_t **create_huffman_codes(long *freqs) { huffcode_t **codes; heap_t *heap; long efreqs[BYTES*2]; int preds[BYTES*2]; int i, extf=BYTES; int r1, r2; memcpy(efreqs, freqs, sizeof(long)*BYTES); memset(&efreqs[BYTES], 0, sizeof(long)*BYTES); heap = _heap_create(BYTES*2, efreqs); if ( heap == NULL ) return NULL; for(i=0; i < BYTES; i++) if ( efreqs[i] > 0 ) _heap_add(heap, i); while( heap->n > 1 ) { r1 = _heap_remove(heap); r2 = _heap_remove(heap); efreqs[extf] = efreqs[r1] + efreqs[r2]; _heap_add(heap, extf); preds[r1] = extf; preds[r2] = -extf; extf++; } r1 = _heap_remove(heap); preds[r1] = r1; _heap_destroy(heap); codes = malloc(sizeof(huffcode_t *)*BYTES); int bc, bn, ix; for(i=0; i < BYTES; i++) { bc=0; bn=0; if ( efreqs[i] == 0 ) { codes[i] = NULL; continue; } ix = i; while( abs(preds[ix]) != ix ) { bc |= ((preds[ix] >= 0) ? 1 : 0 ) << bn; ix = abs(preds[ix]); bn++; } codes[i] = malloc(sizeof(huffcode_t)); codes[i]->nbits = bn; codes[i]->code = bc; } return codes; } void free_huffman_codes(huffcode_t **c) { int i; for(i=0; i < BYTES; i++) free(c[i]); free(c); } #define MAXBITSPERCODE 100 void inttobits(int c, int n, char *s) { s[n] = 0; while(n > 0) { s[n-1] = (c%2) + '0'; c >>= 1; n--; } } const char *test = "this is an example for huffman encoding"; int main() { huffcode_t **r; int i; char strbit[MAXBITSPERCODE]; const char *p; long freqs[BYTES]; memset(freqs, 0, sizeof freqs); p = test; while(*p != '\0') freqs[*p++]++; r = create_huffman_codes(freqs); for(i=0; i < BYTES; i++) { if ( r[i] != NULL ) { inttobits(r[i]->code, r[i]->nbits, strbit); printf("%c (%d) %s\n", i, r[i]->code, strbit); } } free_huffman_codes(r); return 0; }
Produce a language-to-language conversion: from Ada to C++, same semantics.
with Ada.Containers.Indefinite_Ordered_Maps; with Ada.Containers.Ordered_Maps; with Ada.Finalization; generic type Symbol_Type is private; with function "<" (Left, Right : Symbol_Type) return Boolean is <>; with procedure Put (Item : Symbol_Type); type Symbol_Sequence is array (Positive range <>) of Symbol_Type; type Frequency_Type is private; with function "+" (Left, Right : Frequency_Type) return Frequency_Type is <>; with function "<" (Left, Right : Frequency_Type) return Boolean is <>; package Huffman is type Bit_Sequence is array (Positive range <>) of Boolean; Zero_Sequence : constant Bit_Sequence (1 .. 0) := (others => False); procedure Put (Code : Bit_Sequence); package Frequency_Maps is new Ada.Containers.Ordered_Maps (Element_Type => Frequency_Type, Key_Type => Symbol_Type); type Huffman_Tree is private; procedure Create_Tree (Tree : out Huffman_Tree; Frequencies : Frequency_Maps.Map); function Encode (Tree : Huffman_Tree; Symbol : Symbol_Type) return Bit_Sequence; function Encode (Tree : Huffman_Tree; Symbols : Symbol_Sequence) return Bit_Sequence; function Decode (Tree : Huffman_Tree; Code : Bit_Sequence) return Symbol_Sequence; procedure Dump_Encoding (Tree : Huffman_Tree); private package Encoding_Maps is new Ada.Containers.Indefinite_Ordered_Maps (Element_Type => Bit_Sequence, Key_Type => Symbol_Type); type Huffman_Node; type Node_Access is access Huffman_Node; type Huffman_Node is record Frequency : Frequency_Type; Left_Child : Node_Access := null; Right_Child : Node_Access := null; Symbol : Symbol_Type; end record; function Create_Node (Symbol : Symbol_Type; Frequency : Frequency_Type) return Node_Access; function Create_Node (Left, Right : Node_Access) return Node_Access; procedure Fill (The_Node : Node_Access; Map : in out Encoding_Maps.Map; Prefix : Bit_Sequence); type Huffman_Tree is new Ada.Finalization.Controlled with record Tree : Node_Access := null; Map : Encoding_Maps.Map := Encoding_Maps.Empty_Map; end record; overriding procedure Finalize (Object : in out Huffman_Tree); end Huffman;
#include <iostream> #include <queue> #include <map> #include <climits> #include <iterator> #include <algorithm> const int UniqueSymbols = 1 << CHAR_BIT; const char* SampleString = "this is an example for huffman encoding"; typedef std::vector<bool> HuffCode; typedef std::map<char, HuffCode> HuffCodeMap; class INode { public: const int f; virtual ~INode() {} protected: INode(int f) : f(f) {} }; class InternalNode : public INode { public: INode *const left; INode *const right; InternalNode(INode* c0, INode* c1) : INode(c0->f + c1->f), left(c0), right(c1) {} ~InternalNode() { delete left; delete right; } }; class LeafNode : public INode { public: const char c; LeafNode(int f, char c) : INode(f), c(c) {} }; struct NodeCmp { bool operator()(const INode* lhs, const INode* rhs) const { return lhs->f > rhs->f; } }; INode* BuildTree(const int (&frequencies)[UniqueSymbols]) { std::priority_queue<INode*, std::vector<INode*>, NodeCmp> trees; for (int i = 0; i < UniqueSymbols; ++i) { if(frequencies[i] != 0) trees.push(new LeafNode(frequencies[i], (char)i)); } while (trees.size() > 1) { INode* childR = trees.top(); trees.pop(); INode* childL = trees.top(); trees.pop(); INode* parent = new InternalNode(childR, childL); trees.push(parent); } return trees.top(); } void GenerateCodes(const INode* node, const HuffCode& prefix, HuffCodeMap& outCodes) { if (const LeafNode* lf = dynamic_cast<const LeafNode*>(node)) { outCodes[lf->c] = prefix; } else if (const InternalNode* in = dynamic_cast<const InternalNode*>(node)) { HuffCode leftPrefix = prefix; leftPrefix.push_back(false); GenerateCodes(in->left, leftPrefix, outCodes); HuffCode rightPrefix = prefix; rightPrefix.push_back(true); GenerateCodes(in->right, rightPrefix, outCodes); } } int main() { int frequencies[UniqueSymbols] = {0}; const char* ptr = SampleString; while (*ptr != '\0') ++frequencies[*ptr++]; INode* root = BuildTree(frequencies); HuffCodeMap codes; GenerateCodes(root, HuffCode(), codes); delete root; for (HuffCodeMap::const_iterator it = codes.begin(); it != codes.end(); ++it) { std::cout << it->first << " "; std::copy(it->second.begin(), it->second.end(), std::ostream_iterator<bool>(std::cout)); std::cout << std::endl; } return 0; }
Convert this Ada snippet to Go and keep its semantics consistent.
with Ada.Containers.Indefinite_Ordered_Maps; with Ada.Containers.Ordered_Maps; with Ada.Finalization; generic type Symbol_Type is private; with function "<" (Left, Right : Symbol_Type) return Boolean is <>; with procedure Put (Item : Symbol_Type); type Symbol_Sequence is array (Positive range <>) of Symbol_Type; type Frequency_Type is private; with function "+" (Left, Right : Frequency_Type) return Frequency_Type is <>; with function "<" (Left, Right : Frequency_Type) return Boolean is <>; package Huffman is type Bit_Sequence is array (Positive range <>) of Boolean; Zero_Sequence : constant Bit_Sequence (1 .. 0) := (others => False); procedure Put (Code : Bit_Sequence); package Frequency_Maps is new Ada.Containers.Ordered_Maps (Element_Type => Frequency_Type, Key_Type => Symbol_Type); type Huffman_Tree is private; procedure Create_Tree (Tree : out Huffman_Tree; Frequencies : Frequency_Maps.Map); function Encode (Tree : Huffman_Tree; Symbol : Symbol_Type) return Bit_Sequence; function Encode (Tree : Huffman_Tree; Symbols : Symbol_Sequence) return Bit_Sequence; function Decode (Tree : Huffman_Tree; Code : Bit_Sequence) return Symbol_Sequence; procedure Dump_Encoding (Tree : Huffman_Tree); private package Encoding_Maps is new Ada.Containers.Indefinite_Ordered_Maps (Element_Type => Bit_Sequence, Key_Type => Symbol_Type); type Huffman_Node; type Node_Access is access Huffman_Node; type Huffman_Node is record Frequency : Frequency_Type; Left_Child : Node_Access := null; Right_Child : Node_Access := null; Symbol : Symbol_Type; end record; function Create_Node (Symbol : Symbol_Type; Frequency : Frequency_Type) return Node_Access; function Create_Node (Left, Right : Node_Access) return Node_Access; procedure Fill (The_Node : Node_Access; Map : in out Encoding_Maps.Map; Prefix : Bit_Sequence); type Huffman_Tree is new Ada.Finalization.Controlled with record Tree : Node_Access := null; Map : Encoding_Maps.Map := Encoding_Maps.Empty_Map; end record; overriding procedure Finalize (Object : in out Huffman_Tree); end Huffman;
package main import ( "container/heap" "fmt" ) type HuffmanTree interface { Freq() int } type HuffmanLeaf struct { freq int value rune } type HuffmanNode struct { freq int left, right HuffmanTree } func (self HuffmanLeaf) Freq() int { return self.freq } func (self HuffmanNode) Freq() int { return self.freq } type treeHeap []HuffmanTree func (th treeHeap) Len() int { return len(th) } func (th treeHeap) Less(i, j int) bool { return th[i].Freq() < th[j].Freq() } func (th *treeHeap) Push(ele interface{}) { *th = append(*th, ele.(HuffmanTree)) } func (th *treeHeap) Pop() (popped interface{}) { popped = (*th)[len(*th)-1] *th = (*th)[:len(*th)-1] return } func (th treeHeap) Swap(i, j int) { th[i], th[j] = th[j], th[i] } func buildTree(symFreqs map[rune]int) HuffmanTree { var trees treeHeap for c, f := range symFreqs { trees = append(trees, HuffmanLeaf{f, c}) } heap.Init(&trees) for trees.Len() > 1 { a := heap.Pop(&trees).(HuffmanTree) b := heap.Pop(&trees).(HuffmanTree) heap.Push(&trees, HuffmanNode{a.Freq() + b.Freq(), a, b}) } return heap.Pop(&trees).(HuffmanTree) } func printCodes(tree HuffmanTree, prefix []byte) { switch i := tree.(type) { case HuffmanLeaf: fmt.Printf("%c\t%d\t%s\n", i.value, i.freq, string(prefix)) case HuffmanNode: prefix = append(prefix, '0') printCodes(i.left, prefix) prefix = prefix[:len(prefix)-1] prefix = append(prefix, '1') printCodes(i.right, prefix) prefix = prefix[:len(prefix)-1] } } func main() { test := "this is an example for huffman encoding" symFreqs := make(map[rune]int) for _, c := range test { symFreqs[c]++ } tree := buildTree(symFreqs) fmt.Println("SYMBOL\tWEIGHT\tHUFFMAN CODE") printCodes(tree, []byte{}) }
Translate the given Ada code snippet into Java without altering its behavior.
with Ada.Containers.Indefinite_Ordered_Maps; with Ada.Containers.Ordered_Maps; with Ada.Finalization; generic type Symbol_Type is private; with function "<" (Left, Right : Symbol_Type) return Boolean is <>; with procedure Put (Item : Symbol_Type); type Symbol_Sequence is array (Positive range <>) of Symbol_Type; type Frequency_Type is private; with function "+" (Left, Right : Frequency_Type) return Frequency_Type is <>; with function "<" (Left, Right : Frequency_Type) return Boolean is <>; package Huffman is type Bit_Sequence is array (Positive range <>) of Boolean; Zero_Sequence : constant Bit_Sequence (1 .. 0) := (others => False); procedure Put (Code : Bit_Sequence); package Frequency_Maps is new Ada.Containers.Ordered_Maps (Element_Type => Frequency_Type, Key_Type => Symbol_Type); type Huffman_Tree is private; procedure Create_Tree (Tree : out Huffman_Tree; Frequencies : Frequency_Maps.Map); function Encode (Tree : Huffman_Tree; Symbol : Symbol_Type) return Bit_Sequence; function Encode (Tree : Huffman_Tree; Symbols : Symbol_Sequence) return Bit_Sequence; function Decode (Tree : Huffman_Tree; Code : Bit_Sequence) return Symbol_Sequence; procedure Dump_Encoding (Tree : Huffman_Tree); private package Encoding_Maps is new Ada.Containers.Indefinite_Ordered_Maps (Element_Type => Bit_Sequence, Key_Type => Symbol_Type); type Huffman_Node; type Node_Access is access Huffman_Node; type Huffman_Node is record Frequency : Frequency_Type; Left_Child : Node_Access := null; Right_Child : Node_Access := null; Symbol : Symbol_Type; end record; function Create_Node (Symbol : Symbol_Type; Frequency : Frequency_Type) return Node_Access; function Create_Node (Left, Right : Node_Access) return Node_Access; procedure Fill (The_Node : Node_Access; Map : in out Encoding_Maps.Map; Prefix : Bit_Sequence); type Huffman_Tree is new Ada.Finalization.Controlled with record Tree : Node_Access := null; Map : Encoding_Maps.Map := Encoding_Maps.Empty_Map; end record; overriding procedure Finalize (Object : in out Huffman_Tree); end Huffman;
import java.util.*; abstract class HuffmanTree implements Comparable<HuffmanTree> { public final int frequency; public HuffmanTree(int freq) { frequency = freq; } public int compareTo(HuffmanTree tree) { return frequency - tree.frequency; } } class HuffmanLeaf extends HuffmanTree { public final char value; public HuffmanLeaf(int freq, char val) { super(freq); value = val; } } class HuffmanNode extends HuffmanTree { public final HuffmanTree left, right; public HuffmanNode(HuffmanTree l, HuffmanTree r) { super(l.frequency + r.frequency); left = l; right = r; } } public class HuffmanCode { public static HuffmanTree buildTree(int[] charFreqs) { PriorityQueue<HuffmanTree> trees = new PriorityQueue<HuffmanTree>(); for (int i = 0; i < charFreqs.length; i++) if (charFreqs[i] > 0) trees.offer(new HuffmanLeaf(charFreqs[i], (char)i)); assert trees.size() > 0; while (trees.size() > 1) { HuffmanTree a = trees.poll(); HuffmanTree b = trees.poll(); trees.offer(new HuffmanNode(a, b)); } return trees.poll(); } public static void printCodes(HuffmanTree tree, StringBuffer prefix) { assert tree != null; if (tree instanceof HuffmanLeaf) { HuffmanLeaf leaf = (HuffmanLeaf)tree; System.out.println(leaf.value + "\t" + leaf.frequency + "\t" + prefix); } else if (tree instanceof HuffmanNode) { HuffmanNode node = (HuffmanNode)tree; prefix.append('0'); printCodes(node.left, prefix); prefix.deleteCharAt(prefix.length()-1); prefix.append('1'); printCodes(node.right, prefix); prefix.deleteCharAt(prefix.length()-1); } } public static void main(String[] args) { String test = "this is an example for huffman encoding"; int[] charFreqs = new int[256]; for (char c : test.toCharArray()) charFreqs[c]++; HuffmanTree tree = buildTree(charFreqs); System.out.println("SYMBOL\tWEIGHT\tHUFFMAN CODE"); printCodes(tree, new StringBuffer()); } }
Keep all operations the same but rewrite the snippet in Python.
with Ada.Containers.Indefinite_Ordered_Maps; with Ada.Containers.Ordered_Maps; with Ada.Finalization; generic type Symbol_Type is private; with function "<" (Left, Right : Symbol_Type) return Boolean is <>; with procedure Put (Item : Symbol_Type); type Symbol_Sequence is array (Positive range <>) of Symbol_Type; type Frequency_Type is private; with function "+" (Left, Right : Frequency_Type) return Frequency_Type is <>; with function "<" (Left, Right : Frequency_Type) return Boolean is <>; package Huffman is type Bit_Sequence is array (Positive range <>) of Boolean; Zero_Sequence : constant Bit_Sequence (1 .. 0) := (others => False); procedure Put (Code : Bit_Sequence); package Frequency_Maps is new Ada.Containers.Ordered_Maps (Element_Type => Frequency_Type, Key_Type => Symbol_Type); type Huffman_Tree is private; procedure Create_Tree (Tree : out Huffman_Tree; Frequencies : Frequency_Maps.Map); function Encode (Tree : Huffman_Tree; Symbol : Symbol_Type) return Bit_Sequence; function Encode (Tree : Huffman_Tree; Symbols : Symbol_Sequence) return Bit_Sequence; function Decode (Tree : Huffman_Tree; Code : Bit_Sequence) return Symbol_Sequence; procedure Dump_Encoding (Tree : Huffman_Tree); private package Encoding_Maps is new Ada.Containers.Indefinite_Ordered_Maps (Element_Type => Bit_Sequence, Key_Type => Symbol_Type); type Huffman_Node; type Node_Access is access Huffman_Node; type Huffman_Node is record Frequency : Frequency_Type; Left_Child : Node_Access := null; Right_Child : Node_Access := null; Symbol : Symbol_Type; end record; function Create_Node (Symbol : Symbol_Type; Frequency : Frequency_Type) return Node_Access; function Create_Node (Left, Right : Node_Access) return Node_Access; procedure Fill (The_Node : Node_Access; Map : in out Encoding_Maps.Map; Prefix : Bit_Sequence); type Huffman_Tree is new Ada.Finalization.Controlled with record Tree : Node_Access := null; Map : Encoding_Maps.Map := Encoding_Maps.Empty_Map; end record; overriding procedure Finalize (Object : in out Huffman_Tree); end Huffman;
from heapq import heappush, heappop, heapify from collections import defaultdict def encode(symb2freq): heap = [[wt, [sym, ""]] for sym, wt in symb2freq.items()] heapify(heap) while len(heap) > 1: lo = heappop(heap) hi = heappop(heap) for pair in lo[1:]: pair[1] = '0' + pair[1] for pair in hi[1:]: pair[1] = '1' + pair[1] heappush(heap, [lo[0] + hi[0]] + lo[1:] + hi[1:]) return sorted(heappop(heap)[1:], key=lambda p: (len(p[-1]), p)) txt = "this is an example for huffman encoding" symb2freq = defaultdict(int) for ch in txt: symb2freq[ch] += 1 huff = encode(symb2freq) print "Symbol\tWeight\tHuffman Code" for p in huff: print "%s\t%s\t%s" % (p[0], symb2freq[p[0]], p[1])
Transform the following BBC_Basic implementation into C, maintaining the same output and logic.
INSTALL @lib$+"SORTSALIB" SortUp% = FN_sortSAinit(0,0) : SortDn% = FN_sortSAinit(1,0) : Text$ = "this is an example for huffman encoding" DIM tree{(127) ch&, num%, lkl%, lkr%} FOR i% = 1 TO LEN(Text$) c% = ASCMID$(Text$,i%) tree{(c%)}.ch& = c% tree{(c%)}.num% += 1 NEXT C% = DIM(tree{()},1) + 1 CALL SortDn%, tree{()}, tree{(0)}.num% FOR i% = 0 TO DIM(tree{()},1) IF tree{(i%)}.num% = 0 EXIT FOR NEXT size% = i% linked% = 0 REPEAT C% = size% CALL SortUp%, tree{()}, tree{(0)}.num% i% = 0 : WHILE tree{(i%)}.lkl% OR tree{(i%)}.lkr% i% += 1 : ENDWHILE tree{(i%)}.lkl% = size% j% = 0 : WHILE tree{(j%)}.lkl% OR tree{(j%)}.lkr% j% += 1 : ENDWHILE tree{(j%)}.lkr% = size% linked% += 2 tree{(size%)}.num% = tree{(i%)}.num% + tree{(j%)}.num% size% += 1 UNTIL linked% = (size% - 1) FOR i% = size% - 1 TO 0 STEP -1 IF tree{(i%)}.ch& THEN h$ = "" j% = i% REPEAT CASE TRUE OF WHEN tree{(j%)}.lkl% <> 0: h$ = "0" + h$ j% = tree{(j%)}.lkl% WHEN tree{(j%)}.lkr% <> 0: h$ = "1" + h$ j% = tree{(j%)}.lkr% OTHERWISE: EXIT REPEAT ENDCASE UNTIL FALSE VDU tree{(i%)}.ch& : PRINT " " h$ ENDIF NEXT END
#include <stdio.h> #include <stdlib.h> #include <string.h> #define BYTES 256 struct huffcode { int nbits; int code; }; typedef struct huffcode huffcode_t; struct huffheap { int *h; int n, s, cs; long *f; }; typedef struct huffheap heap_t; static heap_t *_heap_create(int s, long *f) { heap_t *h; h = malloc(sizeof(heap_t)); h->h = malloc(sizeof(int)*s); h->s = h->cs = s; h->n = 0; h->f = f; return h; } static void _heap_destroy(heap_t *heap) { free(heap->h); free(heap); } #define swap_(I,J) do { int t_; t_ = a[(I)]; \ a[(I)] = a[(J)]; a[(J)] = t_; } while(0) static void _heap_sort(heap_t *heap) { int i=1, j=2; int *a = heap->h; while(i < heap->n) { if ( heap->f[a[i-1]] >= heap->f[a[i]] ) { i = j; j++; } else { swap_(i-1, i); i--; i = (i==0) ? j++ : i; } } } #undef swap_ static void _heap_add(heap_t *heap, int c) { if ( (heap->n + 1) > heap->s ) { heap->h = realloc(heap->h, heap->s + heap->cs); heap->s += heap->cs; } heap->h[heap->n] = c; heap->n++; _heap_sort(heap); } static int _heap_remove(heap_t *heap) { if ( heap->n > 0 ) { heap->n--; return heap->h[heap->n]; } return -1; } huffcode_t **create_huffman_codes(long *freqs) { huffcode_t **codes; heap_t *heap; long efreqs[BYTES*2]; int preds[BYTES*2]; int i, extf=BYTES; int r1, r2; memcpy(efreqs, freqs, sizeof(long)*BYTES); memset(&efreqs[BYTES], 0, sizeof(long)*BYTES); heap = _heap_create(BYTES*2, efreqs); if ( heap == NULL ) return NULL; for(i=0; i < BYTES; i++) if ( efreqs[i] > 0 ) _heap_add(heap, i); while( heap->n > 1 ) { r1 = _heap_remove(heap); r2 = _heap_remove(heap); efreqs[extf] = efreqs[r1] + efreqs[r2]; _heap_add(heap, extf); preds[r1] = extf; preds[r2] = -extf; extf++; } r1 = _heap_remove(heap); preds[r1] = r1; _heap_destroy(heap); codes = malloc(sizeof(huffcode_t *)*BYTES); int bc, bn, ix; for(i=0; i < BYTES; i++) { bc=0; bn=0; if ( efreqs[i] == 0 ) { codes[i] = NULL; continue; } ix = i; while( abs(preds[ix]) != ix ) { bc |= ((preds[ix] >= 0) ? 1 : 0 ) << bn; ix = abs(preds[ix]); bn++; } codes[i] = malloc(sizeof(huffcode_t)); codes[i]->nbits = bn; codes[i]->code = bc; } return codes; } void free_huffman_codes(huffcode_t **c) { int i; for(i=0; i < BYTES; i++) free(c[i]); free(c); } #define MAXBITSPERCODE 100 void inttobits(int c, int n, char *s) { s[n] = 0; while(n > 0) { s[n-1] = (c%2) + '0'; c >>= 1; n--; } } const char *test = "this is an example for huffman encoding"; int main() { huffcode_t **r; int i; char strbit[MAXBITSPERCODE]; const char *p; long freqs[BYTES]; memset(freqs, 0, sizeof freqs); p = test; while(*p != '\0') freqs[*p++]++; r = create_huffman_codes(freqs); for(i=0; i < BYTES; i++) { if ( r[i] != NULL ) { inttobits(r[i]->code, r[i]->nbits, strbit); printf("%c (%d) %s\n", i, r[i]->code, strbit); } } free_huffman_codes(r); return 0; }
Write a version of this BBC_Basic function in C# with identical behavior.
INSTALL @lib$+"SORTSALIB" SortUp% = FN_sortSAinit(0,0) : SortDn% = FN_sortSAinit(1,0) : Text$ = "this is an example for huffman encoding" DIM tree{(127) ch&, num%, lkl%, lkr%} FOR i% = 1 TO LEN(Text$) c% = ASCMID$(Text$,i%) tree{(c%)}.ch& = c% tree{(c%)}.num% += 1 NEXT C% = DIM(tree{()},1) + 1 CALL SortDn%, tree{()}, tree{(0)}.num% FOR i% = 0 TO DIM(tree{()},1) IF tree{(i%)}.num% = 0 EXIT FOR NEXT size% = i% linked% = 0 REPEAT C% = size% CALL SortUp%, tree{()}, tree{(0)}.num% i% = 0 : WHILE tree{(i%)}.lkl% OR tree{(i%)}.lkr% i% += 1 : ENDWHILE tree{(i%)}.lkl% = size% j% = 0 : WHILE tree{(j%)}.lkl% OR tree{(j%)}.lkr% j% += 1 : ENDWHILE tree{(j%)}.lkr% = size% linked% += 2 tree{(size%)}.num% = tree{(i%)}.num% + tree{(j%)}.num% size% += 1 UNTIL linked% = (size% - 1) FOR i% = size% - 1 TO 0 STEP -1 IF tree{(i%)}.ch& THEN h$ = "" j% = i% REPEAT CASE TRUE OF WHEN tree{(j%)}.lkl% <> 0: h$ = "0" + h$ j% = tree{(j%)}.lkl% WHEN tree{(j%)}.lkr% <> 0: h$ = "1" + h$ j% = tree{(j%)}.lkr% OTHERWISE: EXIT REPEAT ENDCASE UNTIL FALSE VDU tree{(i%)}.ch& : PRINT " " h$ ENDIF NEXT END
using System; using System.Collections.Generic; namespace Huffman_Encoding { public class PriorityQueue<T> where T : IComparable { protected List<T> LstHeap = new List<T>(); public virtual int Count { get { return LstHeap.Count; } } public virtual void Add(T val) { LstHeap.Add(val); SetAt(LstHeap.Count - 1, val); UpHeap(LstHeap.Count - 1); } public virtual T Peek() { if (LstHeap.Count == 0) { throw new IndexOutOfRangeException("Peeking at an empty priority queue"); } return LstHeap[0]; } public virtual T Pop() { if (LstHeap.Count == 0) { throw new IndexOutOfRangeException("Popping an empty priority queue"); } T valRet = LstHeap[0]; SetAt(0, LstHeap[LstHeap.Count - 1]); LstHeap.RemoveAt(LstHeap.Count - 1); DownHeap(0); return valRet; } protected virtual void SetAt(int i, T val) { LstHeap[i] = val; } protected bool RightSonExists(int i) { return RightChildIndex(i) < LstHeap.Count; } protected bool LeftSonExists(int i) { return LeftChildIndex(i) < LstHeap.Count; } protected int ParentIndex(int i) { return (i - 1) / 2; } protected int LeftChildIndex(int i) { return 2 * i + 1; } protected int RightChildIndex(int i) { return 2 * (i + 1); } protected T ArrayVal(int i) { return LstHeap[i]; } protected T Parent(int i) { return LstHeap[ParentIndex(i)]; } protected T Left(int i) { return LstHeap[LeftChildIndex(i)]; } protected T Right(int i) { return LstHeap[RightChildIndex(i)]; } protected void Swap(int i, int j) { T valHold = ArrayVal(i); SetAt(i, LstHeap[j]); SetAt(j, valHold); } protected void UpHeap(int i) { while (i > 0 && ArrayVal(i).CompareTo(Parent(i)) > 0) { Swap(i, ParentIndex(i)); i = ParentIndex(i); } } protected void DownHeap(int i) { while (i >= 0) { int iContinue = -1; if (RightSonExists(i) && Right(i).CompareTo(ArrayVal(i)) > 0) { iContinue = Left(i).CompareTo(Right(i)) < 0 ? RightChildIndex(i) : LeftChildIndex(i); } else if (LeftSonExists(i) && Left(i).CompareTo(ArrayVal(i)) > 0) { iContinue = LeftChildIndex(i); } if (iContinue >= 0 && iContinue < LstHeap.Count) { Swap(i, iContinue); } i = iContinue; } } } internal class HuffmanNode<T> : IComparable { internal HuffmanNode(double probability, T value) { Probability = probability; LeftSon = RightSon = Parent = null; Value = value; IsLeaf = true; } internal HuffmanNode(HuffmanNode<T> leftSon, HuffmanNode<T> rightSon) { LeftSon = leftSon; RightSon = rightSon; Probability = leftSon.Probability + rightSon.Probability; leftSon.IsZero = true; rightSon.IsZero = false; leftSon.Parent = rightSon.Parent = this; IsLeaf = false; } internal HuffmanNode<T> LeftSon { get; set; } internal HuffmanNode<T> RightSon { get; set; } internal HuffmanNode<T> Parent { get; set; } internal T Value { get; set; } internal bool IsLeaf { get; set; } internal bool IsZero { get; set; } internal int Bit { get { return IsZero ? 0 : 1; } } internal bool IsRoot { get { return Parent == null; } } internal double Probability { get; set; } public int CompareTo(object obj) { return -Probability.CompareTo(((HuffmanNode<T>) obj).Probability); } } public class Huffman<T> where T : IComparable { private readonly Dictionary<T, HuffmanNode<T>> _leafDictionary = new Dictionary<T, HuffmanNode<T>>(); private readonly HuffmanNode<T> _root; public Huffman(IEnumerable<T> values) { var counts = new Dictionary<T, int>(); var priorityQueue = new PriorityQueue<HuffmanNode<T>>(); int valueCount = 0; foreach (T value in values) { if (!counts.ContainsKey(value)) { counts[value] = 0; } counts[value]++; valueCount++; } foreach (T value in counts.Keys) { var node = new HuffmanNode<T>((double) counts[value] / valueCount, value); priorityQueue.Add(node); _leafDictionary[value] = node; } while (priorityQueue.Count > 1) { HuffmanNode<T> leftSon = priorityQueue.Pop(); HuffmanNode<T> rightSon = priorityQueue.Pop(); var parent = new HuffmanNode<T>(leftSon, rightSon); priorityQueue.Add(parent); } _root = priorityQueue.Pop(); _root.IsZero = false; } public List<int> Encode(T value) { var returnValue = new List<int>(); Encode(value, returnValue); return returnValue; } public void Encode(T value, List<int> encoding) { if (!_leafDictionary.ContainsKey(value)) { throw new ArgumentException("Invalid value in Encode"); } HuffmanNode<T> nodeCur = _leafDictionary[value]; var reverseEncoding = new List<int>(); while (!nodeCur.IsRoot) { reverseEncoding.Add(nodeCur.Bit); nodeCur = nodeCur.Parent; } reverseEncoding.Reverse(); encoding.AddRange(reverseEncoding); } public List<int> Encode(IEnumerable<T> values) { var returnValue = new List<int>(); foreach (T value in values) { Encode(value, returnValue); } return returnValue; } public T Decode(List<int> bitString, ref int position) { HuffmanNode<T> nodeCur = _root; while (!nodeCur.IsLeaf) { if (position > bitString.Count) { throw new ArgumentException("Invalid bitstring in Decode"); } nodeCur = bitString[position++] == 0 ? nodeCur.LeftSon : nodeCur.RightSon; } return nodeCur.Value; } public List<T> Decode(List<int> bitString) { int position = 0; var returnValue = new List<T>(); while (position != bitString.Count) { returnValue.Add(Decode(bitString, ref position)); } return returnValue; } } internal class Program { private const string Example = "this is an example for huffman encoding"; private static void Main() { var huffman = new Huffman<char>(Example); List<int> encoding = huffman.Encode(Example); List<char> decoding = huffman.Decode(encoding); var outString = new string(decoding.ToArray()); Console.WriteLine(outString == Example ? "Encoding/decoding worked" : "Encoding/Decoding failed"); var chars = new HashSet<char>(Example); foreach (char c in chars) { encoding = huffman.Encode(c); Console.Write("{0}: ", c); foreach (int bit in encoding) { Console.Write("{0}", bit); } Console.WriteLine(); } Console.ReadKey(); } } }
Preserve the algorithm and functionality while converting the code from BBC_Basic to C++.
INSTALL @lib$+"SORTSALIB" SortUp% = FN_sortSAinit(0,0) : SortDn% = FN_sortSAinit(1,0) : Text$ = "this is an example for huffman encoding" DIM tree{(127) ch&, num%, lkl%, lkr%} FOR i% = 1 TO LEN(Text$) c% = ASCMID$(Text$,i%) tree{(c%)}.ch& = c% tree{(c%)}.num% += 1 NEXT C% = DIM(tree{()},1) + 1 CALL SortDn%, tree{()}, tree{(0)}.num% FOR i% = 0 TO DIM(tree{()},1) IF tree{(i%)}.num% = 0 EXIT FOR NEXT size% = i% linked% = 0 REPEAT C% = size% CALL SortUp%, tree{()}, tree{(0)}.num% i% = 0 : WHILE tree{(i%)}.lkl% OR tree{(i%)}.lkr% i% += 1 : ENDWHILE tree{(i%)}.lkl% = size% j% = 0 : WHILE tree{(j%)}.lkl% OR tree{(j%)}.lkr% j% += 1 : ENDWHILE tree{(j%)}.lkr% = size% linked% += 2 tree{(size%)}.num% = tree{(i%)}.num% + tree{(j%)}.num% size% += 1 UNTIL linked% = (size% - 1) FOR i% = size% - 1 TO 0 STEP -1 IF tree{(i%)}.ch& THEN h$ = "" j% = i% REPEAT CASE TRUE OF WHEN tree{(j%)}.lkl% <> 0: h$ = "0" + h$ j% = tree{(j%)}.lkl% WHEN tree{(j%)}.lkr% <> 0: h$ = "1" + h$ j% = tree{(j%)}.lkr% OTHERWISE: EXIT REPEAT ENDCASE UNTIL FALSE VDU tree{(i%)}.ch& : PRINT " " h$ ENDIF NEXT END
#include <iostream> #include <queue> #include <map> #include <climits> #include <iterator> #include <algorithm> const int UniqueSymbols = 1 << CHAR_BIT; const char* SampleString = "this is an example for huffman encoding"; typedef std::vector<bool> HuffCode; typedef std::map<char, HuffCode> HuffCodeMap; class INode { public: const int f; virtual ~INode() {} protected: INode(int f) : f(f) {} }; class InternalNode : public INode { public: INode *const left; INode *const right; InternalNode(INode* c0, INode* c1) : INode(c0->f + c1->f), left(c0), right(c1) {} ~InternalNode() { delete left; delete right; } }; class LeafNode : public INode { public: const char c; LeafNode(int f, char c) : INode(f), c(c) {} }; struct NodeCmp { bool operator()(const INode* lhs, const INode* rhs) const { return lhs->f > rhs->f; } }; INode* BuildTree(const int (&frequencies)[UniqueSymbols]) { std::priority_queue<INode*, std::vector<INode*>, NodeCmp> trees; for (int i = 0; i < UniqueSymbols; ++i) { if(frequencies[i] != 0) trees.push(new LeafNode(frequencies[i], (char)i)); } while (trees.size() > 1) { INode* childR = trees.top(); trees.pop(); INode* childL = trees.top(); trees.pop(); INode* parent = new InternalNode(childR, childL); trees.push(parent); } return trees.top(); } void GenerateCodes(const INode* node, const HuffCode& prefix, HuffCodeMap& outCodes) { if (const LeafNode* lf = dynamic_cast<const LeafNode*>(node)) { outCodes[lf->c] = prefix; } else if (const InternalNode* in = dynamic_cast<const InternalNode*>(node)) { HuffCode leftPrefix = prefix; leftPrefix.push_back(false); GenerateCodes(in->left, leftPrefix, outCodes); HuffCode rightPrefix = prefix; rightPrefix.push_back(true); GenerateCodes(in->right, rightPrefix, outCodes); } } int main() { int frequencies[UniqueSymbols] = {0}; const char* ptr = SampleString; while (*ptr != '\0') ++frequencies[*ptr++]; INode* root = BuildTree(frequencies); HuffCodeMap codes; GenerateCodes(root, HuffCode(), codes); delete root; for (HuffCodeMap::const_iterator it = codes.begin(); it != codes.end(); ++it) { std::cout << it->first << " "; std::copy(it->second.begin(), it->second.end(), std::ostream_iterator<bool>(std::cout)); std::cout << std::endl; } return 0; }
Change the following BBC_Basic code into Java without altering its purpose.
INSTALL @lib$+"SORTSALIB" SortUp% = FN_sortSAinit(0,0) : SortDn% = FN_sortSAinit(1,0) : Text$ = "this is an example for huffman encoding" DIM tree{(127) ch&, num%, lkl%, lkr%} FOR i% = 1 TO LEN(Text$) c% = ASCMID$(Text$,i%) tree{(c%)}.ch& = c% tree{(c%)}.num% += 1 NEXT C% = DIM(tree{()},1) + 1 CALL SortDn%, tree{()}, tree{(0)}.num% FOR i% = 0 TO DIM(tree{()},1) IF tree{(i%)}.num% = 0 EXIT FOR NEXT size% = i% linked% = 0 REPEAT C% = size% CALL SortUp%, tree{()}, tree{(0)}.num% i% = 0 : WHILE tree{(i%)}.lkl% OR tree{(i%)}.lkr% i% += 1 : ENDWHILE tree{(i%)}.lkl% = size% j% = 0 : WHILE tree{(j%)}.lkl% OR tree{(j%)}.lkr% j% += 1 : ENDWHILE tree{(j%)}.lkr% = size% linked% += 2 tree{(size%)}.num% = tree{(i%)}.num% + tree{(j%)}.num% size% += 1 UNTIL linked% = (size% - 1) FOR i% = size% - 1 TO 0 STEP -1 IF tree{(i%)}.ch& THEN h$ = "" j% = i% REPEAT CASE TRUE OF WHEN tree{(j%)}.lkl% <> 0: h$ = "0" + h$ j% = tree{(j%)}.lkl% WHEN tree{(j%)}.lkr% <> 0: h$ = "1" + h$ j% = tree{(j%)}.lkr% OTHERWISE: EXIT REPEAT ENDCASE UNTIL FALSE VDU tree{(i%)}.ch& : PRINT " " h$ ENDIF NEXT END
import java.util.*; abstract class HuffmanTree implements Comparable<HuffmanTree> { public final int frequency; public HuffmanTree(int freq) { frequency = freq; } public int compareTo(HuffmanTree tree) { return frequency - tree.frequency; } } class HuffmanLeaf extends HuffmanTree { public final char value; public HuffmanLeaf(int freq, char val) { super(freq); value = val; } } class HuffmanNode extends HuffmanTree { public final HuffmanTree left, right; public HuffmanNode(HuffmanTree l, HuffmanTree r) { super(l.frequency + r.frequency); left = l; right = r; } } public class HuffmanCode { public static HuffmanTree buildTree(int[] charFreqs) { PriorityQueue<HuffmanTree> trees = new PriorityQueue<HuffmanTree>(); for (int i = 0; i < charFreqs.length; i++) if (charFreqs[i] > 0) trees.offer(new HuffmanLeaf(charFreqs[i], (char)i)); assert trees.size() > 0; while (trees.size() > 1) { HuffmanTree a = trees.poll(); HuffmanTree b = trees.poll(); trees.offer(new HuffmanNode(a, b)); } return trees.poll(); } public static void printCodes(HuffmanTree tree, StringBuffer prefix) { assert tree != null; if (tree instanceof HuffmanLeaf) { HuffmanLeaf leaf = (HuffmanLeaf)tree; System.out.println(leaf.value + "\t" + leaf.frequency + "\t" + prefix); } else if (tree instanceof HuffmanNode) { HuffmanNode node = (HuffmanNode)tree; prefix.append('0'); printCodes(node.left, prefix); prefix.deleteCharAt(prefix.length()-1); prefix.append('1'); printCodes(node.right, prefix); prefix.deleteCharAt(prefix.length()-1); } } public static void main(String[] args) { String test = "this is an example for huffman encoding"; int[] charFreqs = new int[256]; for (char c : test.toCharArray()) charFreqs[c]++; HuffmanTree tree = buildTree(charFreqs); System.out.println("SYMBOL\tWEIGHT\tHUFFMAN CODE"); printCodes(tree, new StringBuffer()); } }