Instruction stringlengths 45 106 | input_code stringlengths 1 13.7k | output_code stringlengths 1 13.7k |
|---|---|---|
Generate a PHP translation of this Delphi snippet without changing its computational steps. | procedure ShowRadixOutput(Memo: TMemo);
var I: integer;
begin
I:=123456789;
Memo.Lines.Add('Decimal Hexadecimal');
Memo.Lines.Add('-----------------------');
Memo.Lines.Add(IntToStr(I)+' - '+IntToHex(I,8));
end;
| <?php
foreach (range(0, 33) as $n) {
echo decbin($n), "\t", decoct($n), "\t", $n, "\t", dechex($n), "\n";
}
?>
|
Preserve the algorithm and functionality while converting the code from Elixir to PHP. | Enum.each(0..32, fn i -> :io.format "~2w :~6.2B, ~2.8B, ~2.16B~n", [i,i,i,i] end)
| <?php
foreach (range(0, 33) as $n) {
echo decbin($n), "\t", decoct($n), "\t", $n, "\t", dechex($n), "\n";
}
?>
|
Maintain the same structure and functionality when rewriting this code in PHP. | let ns = [30..33]
ns |> Seq.iter (fun n -> printfn " %3o %2d %2X" n n n)
| <?php
foreach (range(0, 33) as $n) {
echo decbin($n), "\t", decoct($n), "\t", $n, "\t", dechex($n), "\n";
}
?>
|
Convert this Factor block to PHP, preserving its control flow and logic. | 1234567 2 36 [a,b] [ >base print ] with each
| <?php
foreach (range(0, 33) as $n) {
echo decbin($n), "\t", decoct($n), "\t", $n, "\t", dechex($n), "\n";
}
?>
|
Keep all operations the same but rewrite the snippet in PHP. | : main 34 1 do cr i dec. i hex. loop ;
main
...
11 $B
...
| <?php
foreach (range(0, 33) as $n) {
echo decbin($n), "\t", decoct($n), "\t", $n, "\t", dechex($n), "\n";
}
?>
|
Write a version of this Fortran function in PHP with identical behavior. | do n = 1, 33
write(*, "(b6, o4, i4, z4)") n, n, n, n
end do
| <?php
foreach (range(0, 33) as $n) {
echo decbin($n), "\t", decoct($n), "\t", $n, "\t", dechex($n), "\n";
}
?>
|
Write the same algorithm in PHP as shown in this Haskell implementation. | import Text.Printf
main :: IO ()
main = mapM_ f [0..33] where
f :: Int -> IO ()
f n = printf " %3o %2d %2X\n" n n n
| <?php
foreach (range(0, 33) as $n) {
echo decbin($n), "\t", decoct($n), "\t", $n, "\t", dechex($n), "\n";
}
?>
|
Produce a functionally identical PHP code for the snippet given in Icon. | procedure main()
write("Non-decimal radices/Output")
every i := 255 | 2 | 5 | 16 do {
printf("%%d = %d\n",i)
printf("%%x = %x\n",i)
printf("%%o = %o\n",i)
printf("%%s = %s\n",i)
printf("%%i = %i\n",i)
}
end
| <?php
foreach (range(0, 33) as $n) {
echo decbin($n), "\t", decoct($n), "\t", $n, "\t", dechex($n), "\n";
}
?>
|
Produce a language-to-language conversion: from J to PHP, same semantics. | 2 #.inv 12
1 1 0 0
3 #.inv 100
1 0 2 0 1
16 #.inv 180097588
10 11 12 1 2 3 4
| <?php
foreach (range(0, 33) as $n) {
echo decbin($n), "\t", decoct($n), "\t", $n, "\t", dechex($n), "\n";
}
?>
|
Produce a language-to-language conversion: from Julia to PHP, same semantics. | using Primes, Printf
println("Primes ≤ $hi written in common bases.")
@printf("%8s%8s%8s%8s", "bin", "oct", "dec", "hex")
for i in primes(50)
@printf("%8s%8s%8s%8s\n", bin(i), oct(i), dec(i), hex(i))
end
| <?php
foreach (range(0, 33) as $n) {
echo decbin($n), "\t", decoct($n), "\t", $n, "\t", dechex($n), "\n";
}
?>
|
Generate a PHP translation of this Lua snippet without changing its computational steps. | for i = 1, 33 do
print( string.format( "%o \t %d \t %x", i, i, i ) )
end
| <?php
foreach (range(0, 33) as $n) {
echo decbin($n), "\t", decoct($n), "\t", $n, "\t", dechex($n), "\n";
}
?>
|
Change the following Mathematica code into PHP without altering its purpose. | Table[IntegerString[n,b], {n,Range@38}, {b,{2,8,16,36}}] // Grid
| <?php
foreach (range(0, 33) as $n) {
echo decbin($n), "\t", decoct($n), "\t", $n, "\t", dechex($n), "\n";
}
?>
|
Produce a functionally identical PHP code for the snippet given in MATLAB. | fprintf('
| <?php
foreach (range(0, 33) as $n) {
echo decbin($n), "\t", decoct($n), "\t", $n, "\t", dechex($n), "\n";
}
?>
|
Port the following code from Nim to PHP with equivalent syntax and logic. | import strutils
for i in 0..33:
echo toBin(i, 6)," ",toOct(i, 3)," ",align($i,2)," ",toHex(i,2)
| <?php
foreach (range(0, 33) as $n) {
echo decbin($n), "\t", decoct($n), "\t", $n, "\t", dechex($n), "\n";
}
?>
|
Convert the following code from OCaml to PHP, ensuring the logic remains intact. | for n = 0 to 33 do
Printf.printf " %3o %2d %2X\n" n n n
done
| <?php
foreach (range(0, 33) as $n) {
echo decbin($n), "\t", decoct($n), "\t", $n, "\t", dechex($n), "\n";
}
?>
|
Rewrite this program in PHP while keeping its functionality equivalent to the Perl version. | foreach my $n (0..33) {
printf " %6b %3o %2d %2X\n", $n, $n, $n, $n;
}
| <?php
foreach (range(0, 33) as $n) {
echo decbin($n), "\t", decoct($n), "\t", $n, "\t", dechex($n), "\n";
}
?>
|
Convert this PowerShell snippet to PHP and keep its semantics consistent. | foreach ($n in 0..33) {
"Base 2: " + [Convert]::ToString($n, 2)
"Base 8: " + [Convert]::ToString($n, 8)
"Base 10: " + $n
"Base 10: " + [Convert]::ToString($n, 10)
"Base 10: " + ("{0:D}" -f $n)
"Base 16: " + [Convert]::ToString($n, 16)
"Base 16: " + ("{0:X}" -f $n)
}
| <?php
foreach (range(0, 33) as $n) {
echo decbin($n), "\t", decoct($n), "\t", $n, "\t", dechex($n), "\n";
}
?>
|
Port the following code from R to PHP with equivalent syntax and logic. |
as.octmode(x)
as.hexmode(x)
as.integer(x)
as.numeric(x)
| <?php
foreach (range(0, 33) as $n) {
echo decbin($n), "\t", decoct($n), "\t", $n, "\t", dechex($n), "\n";
}
?>
|
Convert this Racket block to PHP, preserving its control flow and logic. | #lang racket
(map (λ(r) (number->string 123 r)) '(2 8 10 16))
(for/list ([r (in-range 2 37)]) (~r 123 #:base r))
| <?php
foreach (range(0, 33) as $n) {
echo decbin($n), "\t", decoct($n), "\t", $n, "\t", dechex($n), "\n";
}
?>
|
Generate a PHP translation of this REXX snippet without changing its computational steps. |
options replace format comments java crossref symbols nobinary
import java.util.Formatter
loop i_ = 1 to 3
loop n_ = 20 to 20000 by 2131
select case i_
when 1 then say useBif(n_)
when 2 then say useJavaFormat(n_)
when 3 then say useJavaNumber(n_)
otherwise nop
end
end n_
say
end i_
return
-- NetRexx doesn't have a decimal to octal conversion
method useBif(n_) public static
d_ = '_'
return '[Base 16='n_.d2x().right(8)',Base 10='n_.right(8)',Base 8='d_.right(8)',Base 2='n_.d2x().x2b().right(20)']'
-- Some of Java's java.lang.Number classes have conversion methods
method useJavaNumber(n_) public static
nx = Long.toHexString(n_)
nd = Long.toString(n_)
no = Long.toOctalString(n_)
nb = Long.toBinaryString(n_)
return '[Base 16='Rexx(nx).right(8)',Base 10='Rexx(nd).right(8)',Base 8='Rexx(no).right(8)',Base 2='Rexx(nb).right(20)']'
-- Java Formatter doesn't have a decimal to binary conversion
method useJavaFormat(n_) public static
fb = StringBuilder()
fm = Formatter(fb)
fm.format("[Base 16=%1$8x,Base 10=%1$8d,Base 8=%1$8o,Base 2=%2$20s]", [Object Long(n_), String('_')])
return fb.toString()
| <?php
foreach (range(0, 33) as $n) {
echo decbin($n), "\t", decoct($n), "\t", $n, "\t", dechex($n), "\n";
}
?>
|
Maintain the same structure and functionality when rewriting this code in PHP. | for n in 0..33
puts " %6b %3o %2d %2X" % [n, n, n, n]
end
puts
[2,8,10,16,36].each {|i| puts " 100.to_s(
| <?php
foreach (range(0, 33) as $n) {
echo decbin($n), "\t", decoct($n), "\t", $n, "\t", dechex($n), "\n";
}
?>
|
Please provide an equivalent version of this Scala code in PHP. |
fun main(args: Array<String>) {
val bases = intArrayOf(2, 8, 10, 16, 19, 36)
for (base in bases) print("%6s".format(base))
println()
println("-".repeat(6 * bases.size))
for (i in 0..35) {
for (base in bases) print("%6s".format(i.toString(base)))
println()
}
}
| <?php
foreach (range(0, 33) as $n) {
echo decbin($n), "\t", decoct($n), "\t", $n, "\t", dechex($n), "\n";
}
?>
|
Keep all operations the same but rewrite the snippet in PHP. | for {set n 0} {$n <= 33} {incr n} {
puts [format " %3o %2d %2X" $n $n $n]
}
| <?php
foreach (range(0, 33) as $n) {
echo decbin($n), "\t", decoct($n), "\t", $n, "\t", dechex($n), "\n";
}
?>
|
Port the provided C code into Rust while preserving the original functionality. | #include <stdio.h>
int main()
{
int i;
for(i=1; i <= 33; i++)
printf("%6d %6x %6o\n", i, i, i);
return 0;
}
| fn main() {
println!("Binary: {:b}", 0xdeadbeefu32);
println!("Binary with 0b prefix: {:#b}", 0xdeadbeefu32);
println!("Octal: {:o}", 0xdeadbeefu32);
println!("Octal with 0o prefix: {:#o}", 0xdeadbeefu32);
println!("Decimal: {}", 0xdeadbeefu32);
println!("Lowercase hexadecimal: {:x}", 0xdeadbeefu32);
println!("Lowercase hexadecimal with 0x prefix: {:#x}", 0xdeadbeefu32);
println!("Uppercase hexadecimal: {:X}", 0xdeadbeefu32);
println!("Uppercase hexadecimal with 0x prefix: {:#X}", 0xdeadbeefu32);
}
|
Convert this C++ block to Rust, preserving its control flow and logic. | #include <iostream>
#include <iomanip>
int main()
{
for (int i = 0; i <= 33; i++)
std::cout << std::setw(6) << std::dec << i << " "
<< std::setw(6) << std::hex << i << " "
<< std::setw(6) << std::oct << i << std::endl;
return 0;
}
| fn main() {
println!("Binary: {:b}", 0xdeadbeefu32);
println!("Binary with 0b prefix: {:#b}", 0xdeadbeefu32);
println!("Octal: {:o}", 0xdeadbeefu32);
println!("Octal with 0o prefix: {:#o}", 0xdeadbeefu32);
println!("Decimal: {}", 0xdeadbeefu32);
println!("Lowercase hexadecimal: {:x}", 0xdeadbeefu32);
println!("Lowercase hexadecimal with 0x prefix: {:#x}", 0xdeadbeefu32);
println!("Uppercase hexadecimal: {:X}", 0xdeadbeefu32);
println!("Uppercase hexadecimal with 0x prefix: {:#X}", 0xdeadbeefu32);
}
|
Rewrite the snippet below in Rust so it works the same as the original C# code. | using System;
namespace NonDecimalRadicesOutput
{
class Program
{
static void Main(string[] args)
{
for (int i = 0; i < 42; i++)
{
string binary = Convert.ToString(i, 2);
string octal = Convert.ToString(i, 8);
string hexadecimal = Convert.ToString(i, 16);
Console.WriteLine(string.Format("Decimal: {0}, Binary: {1}, Octal: {2}, Hexadecimal: {3}", i, binary, octal, hexadecimal));
}
Console.ReadKey();
}
}
}
| fn main() {
println!("Binary: {:b}", 0xdeadbeefu32);
println!("Binary with 0b prefix: {:#b}", 0xdeadbeefu32);
println!("Octal: {:o}", 0xdeadbeefu32);
println!("Octal with 0o prefix: {:#o}", 0xdeadbeefu32);
println!("Decimal: {}", 0xdeadbeefu32);
println!("Lowercase hexadecimal: {:x}", 0xdeadbeefu32);
println!("Lowercase hexadecimal with 0x prefix: {:#x}", 0xdeadbeefu32);
println!("Uppercase hexadecimal: {:X}", 0xdeadbeefu32);
println!("Uppercase hexadecimal with 0x prefix: {:#X}", 0xdeadbeefu32);
}
|
Rewrite this program in Rust while keeping its functionality equivalent to the Go version. | package main
import (
"fmt"
"math/big"
"strconv"
)
func main() {
fmt.Printf("%b\n", 13)
fmt.Printf("%o\n", 13)
fmt.Printf("%d\n", 13)
fmt.Printf("%x\n", 13)
d := big.NewInt(13)
fmt.Printf("%b\n", d)
fmt.Printf("%o\n", d)
fmt.Printf("%d\n", d)
fmt.Printf("%x\n", d)
fmt.Println(strconv.FormatInt(1313, 19))
}
| fn main() {
println!("Binary: {:b}", 0xdeadbeefu32);
println!("Binary with 0b prefix: {:#b}", 0xdeadbeefu32);
println!("Octal: {:o}", 0xdeadbeefu32);
println!("Octal with 0o prefix: {:#o}", 0xdeadbeefu32);
println!("Decimal: {}", 0xdeadbeefu32);
println!("Lowercase hexadecimal: {:x}", 0xdeadbeefu32);
println!("Lowercase hexadecimal with 0x prefix: {:#x}", 0xdeadbeefu32);
println!("Uppercase hexadecimal: {:X}", 0xdeadbeefu32);
println!("Uppercase hexadecimal with 0x prefix: {:#X}", 0xdeadbeefu32);
}
|
Ensure the translated Rust code behaves exactly like the original Java snippet. | public static void main(String args[]){
for(int a= 0;a < 33;a++){
System.out.println(Integer.toBinaryString(a));
System.out.println(Integer.toOctalString(a));
System.out.println(Integer.toHexString(a));
System.out.printf("%3o %2d %2x\n",a ,a ,a);
}
}
| fn main() {
println!("Binary: {:b}", 0xdeadbeefu32);
println!("Binary with 0b prefix: {:#b}", 0xdeadbeefu32);
println!("Octal: {:o}", 0xdeadbeefu32);
println!("Octal with 0o prefix: {:#o}", 0xdeadbeefu32);
println!("Decimal: {}", 0xdeadbeefu32);
println!("Lowercase hexadecimal: {:x}", 0xdeadbeefu32);
println!("Lowercase hexadecimal with 0x prefix: {:#x}", 0xdeadbeefu32);
println!("Uppercase hexadecimal: {:X}", 0xdeadbeefu32);
println!("Uppercase hexadecimal with 0x prefix: {:#X}", 0xdeadbeefu32);
}
|
Port the provided Rust code into Python while preserving the original functionality. | fn main() {
println!("Binary: {:b}", 0xdeadbeefu32);
println!("Binary with 0b prefix: {:#b}", 0xdeadbeefu32);
println!("Octal: {:o}", 0xdeadbeefu32);
println!("Octal with 0o prefix: {:#o}", 0xdeadbeefu32);
println!("Decimal: {}", 0xdeadbeefu32);
println!("Lowercase hexadecimal: {:x}", 0xdeadbeefu32);
println!("Lowercase hexadecimal with 0x prefix: {:#x}", 0xdeadbeefu32);
println!("Uppercase hexadecimal: {:X}", 0xdeadbeefu32);
println!("Uppercase hexadecimal with 0x prefix: {:#X}", 0xdeadbeefu32);
}
| >>> for n in range(34):
print " {0:6b} {1:3o} {2:2d} {3:2X}".format(n, n, n, n)
0 0 0 0
1 1 1 1
10 2 2 2
11 3 3 3
100 4 4 4
101 5 5 5
110 6 6 6
111 7 7 7
1000 10 8 8
1001 11 9 9
1010 12 10 A
1011 13 11 B
1100 14 12 C
1101 15 13 D
1110 16 14 E
1111 17 15 F
10000 20 16 10
10001 21 17 11
10010 22 18 12
10011 23 19 13
10100 24 20 14
10101 25 21 15
10110 26 22 16
10111 27 23 17
11000 30 24 18
11001 31 25 19
11010 32 26 1A
11011 33 27 1B
11100 34 28 1C
11101 35 29 1D
11110 36 30 1E
11111 37 31 1F
100000 40 32 20
100001 41 33 21
>>>
|
Change the programming language of this snippet from Ada to C# without modifying what it does. | package Morse is
type Symbols is (Nul, '-', '.', ' ');
Dash : constant Symbols := '-';
Dot : constant Symbols := '.';
type Morse_Str is array (Positive range <>) of Symbols;
pragma Pack (Morse_Str);
function Convert (Input : String) return Morse_Str;
procedure Morsebeep (Input : Morse_Str);
private
subtype Reschars is Character range ' ' .. 'Z';
subtype Length is Natural range 1 .. 5;
subtype Codes is Morse_Str (Length);
type Codings is record
L : Length;
Code : Codes;
end record;
Table : constant array (Reschars) of Codings :=
('A' => (2, ".- "), 'B' => (4, "-... "), 'C' => (4, "-.-. "),
'D' => (3, "-.. "), 'E' => (1, ". "), 'F' => (4, "..-. "),
'G' => (3, "
'J' => (4, ".
'M' => (2, "
'P' => (4, ".
'S' => (3, "... "), 'T' => (1, "- "), 'U' => (3, "..- "),
'V' => (4, "...- "), 'W' => (3, ".
'Y' => (4, "-.
'2' => (5, "..
'5' => (5, "....."), '6' => (5, "-...."), '7' => (5, "
'8' => (5, "
others => (1, " "));
end 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 the following code from Ada to C, ensuring the logic remains intact. | package Morse is
type Symbols is (Nul, '-', '.', ' ');
Dash : constant Symbols := '-';
Dot : constant Symbols := '.';
type Morse_Str is array (Positive range <>) of Symbols;
pragma Pack (Morse_Str);
function Convert (Input : String) return Morse_Str;
procedure Morsebeep (Input : Morse_Str);
private
subtype Reschars is Character range ' ' .. 'Z';
subtype Length is Natural range 1 .. 5;
subtype Codes is Morse_Str (Length);
type Codings is record
L : Length;
Code : Codes;
end record;
Table : constant array (Reschars) of Codings :=
('A' => (2, ".- "), 'B' => (4, "-... "), 'C' => (4, "-.-. "),
'D' => (3, "-.. "), 'E' => (1, ". "), 'F' => (4, "..-. "),
'G' => (3, "
'J' => (4, ".
'M' => (2, "
'P' => (4, ".
'S' => (3, "... "), 'T' => (1, "- "), 'U' => (3, "..- "),
'V' => (4, "...- "), 'W' => (3, ".
'Y' => (4, "-.
'2' => (5, "..
'5' => (5, "....."), '6' => (5, "-...."), '7' => (5, "
'8' => (5, "
others => (1, " "));
end 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 the given Ada code snippet into Go without altering its behavior. | package Morse is
type Symbols is (Nul, '-', '.', ' ');
Dash : constant Symbols := '-';
Dot : constant Symbols := '.';
type Morse_Str is array (Positive range <>) of Symbols;
pragma Pack (Morse_Str);
function Convert (Input : String) return Morse_Str;
procedure Morsebeep (Input : Morse_Str);
private
subtype Reschars is Character range ' ' .. 'Z';
subtype Length is Natural range 1 .. 5;
subtype Codes is Morse_Str (Length);
type Codings is record
L : Length;
Code : Codes;
end record;
Table : constant array (Reschars) of Codings :=
('A' => (2, ".- "), 'B' => (4, "-... "), 'C' => (4, "-.-. "),
'D' => (3, "-.. "), 'E' => (1, ". "), 'F' => (4, "..-. "),
'G' => (3, "
'J' => (4, ".
'M' => (2, "
'P' => (4, ".
'S' => (3, "... "), 'T' => (1, "- "), 'U' => (3, "..- "),
'V' => (4, "...- "), 'W' => (3, ".
'Y' => (4, "-.
'2' => (5, "..
'5' => (5, "....."), '6' => (5, "-...."), '7' => (5, "
'8' => (5, "
others => (1, " "));
end 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
}
|
Produce a functionally identical Java code for the snippet given in Ada. | package Morse is
type Symbols is (Nul, '-', '.', ' ');
Dash : constant Symbols := '-';
Dot : constant Symbols := '.';
type Morse_Str is array (Positive range <>) of Symbols;
pragma Pack (Morse_Str);
function Convert (Input : String) return Morse_Str;
procedure Morsebeep (Input : Morse_Str);
private
subtype Reschars is Character range ' ' .. 'Z';
subtype Length is Natural range 1 .. 5;
subtype Codes is Morse_Str (Length);
type Codings is record
L : Length;
Code : Codes;
end record;
Table : constant array (Reschars) of Codings :=
('A' => (2, ".- "), 'B' => (4, "-... "), 'C' => (4, "-.-. "),
'D' => (3, "-.. "), 'E' => (1, ". "), 'F' => (4, "..-. "),
'G' => (3, "
'J' => (4, ".
'M' => (2, "
'P' => (4, ".
'S' => (3, "... "), 'T' => (1, "- "), 'U' => (3, "..- "),
'V' => (4, "...- "), 'W' => (3, ".
'Y' => (4, "-.
'2' => (5, "..
'5' => (5, "....."), '6' => (5, "-...."), '7' => (5, "
'8' => (5, "
others => (1, " "));
end 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");
}
}
|
Transform the following Ada implementation into Python, maintaining the same output and logic. | package Morse is
type Symbols is (Nul, '-', '.', ' ');
Dash : constant Symbols := '-';
Dot : constant Symbols := '.';
type Morse_Str is array (Positive range <>) of Symbols;
pragma Pack (Morse_Str);
function Convert (Input : String) return Morse_Str;
procedure Morsebeep (Input : Morse_Str);
private
subtype Reschars is Character range ' ' .. 'Z';
subtype Length is Natural range 1 .. 5;
subtype Codes is Morse_Str (Length);
type Codings is record
L : Length;
Code : Codes;
end record;
Table : constant array (Reschars) of Codings :=
('A' => (2, ".- "), 'B' => (4, "-... "), 'C' => (4, "-.-. "),
'D' => (3, "-.. "), 'E' => (1, ". "), 'F' => (4, "..-. "),
'G' => (3, "
'J' => (4, ".
'M' => (2, "
'P' => (4, ".
'S' => (3, "... "), 'T' => (1, "- "), 'U' => (3, "..- "),
'V' => (4, "...- "), 'W' => (3, ".
'Y' => (4, "-.
'2' => (5, "..
'5' => (5, "....."), '6' => (5, "-...."), '7' => (5, "
'8' => (5, "
others => (1, " "));
end 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 this Ada block to VB, preserving its control flow and logic. | package Morse is
type Symbols is (Nul, '-', '.', ' ');
Dash : constant Symbols := '-';
Dot : constant Symbols := '.';
type Morse_Str is array (Positive range <>) of Symbols;
pragma Pack (Morse_Str);
function Convert (Input : String) return Morse_Str;
procedure Morsebeep (Input : Morse_Str);
private
subtype Reschars is Character range ' ' .. 'Z';
subtype Length is Natural range 1 .. 5;
subtype Codes is Morse_Str (Length);
type Codings is record
L : Length;
Code : Codes;
end record;
Table : constant array (Reschars) of Codings :=
('A' => (2, ".- "), 'B' => (4, "-... "), 'C' => (4, "-.-. "),
'D' => (3, "-.. "), 'E' => (1, ". "), 'F' => (4, "..-. "),
'G' => (3, "
'J' => (4, ".
'M' => (2, "
'P' => (4, ".
'S' => (3, "... "), 'T' => (1, "- "), 'U' => (3, "..- "),
'V' => (4, "...- "), 'W' => (3, ".
'Y' => (4, "-.
'2' => (5, "..
'5' => (5, "....."), '6' => (5, "-...."), '7' => (5, "
'8' => (5, "
others => (1, " "));
end 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
|
Maintain the same structure and functionality when rewriting this code in C. |
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": "----."
]
str: "hello world 2019"
out: ""
loop split str 'ch [
if not? whitespace? ch -> 'out ++ code\[ch]
'out ++ " "
]
print out
|
#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;
}
|
Change the following Arturo code into C# without altering its purpose. |
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": "----."
]
str: "hello world 2019"
out: ""
loop split str 'ch [
if not? whitespace? ch -> 'out ++ code\[ch]
'out ++ " "
]
print out
| 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 Arturo version. |
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": "----."
]
str: "hello world 2019"
out: ""
loop split str 'ch [
if not? whitespace? ch -> 'out ++ code\[ch]
'out ++ " "
]
print out
| 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 provided Arturo code into Python while preserving the original functionality. |
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": "----."
]
str: "hello world 2019"
out: ""
loop split str 'ch [
if not? whitespace? ch -> 'out ++ code\[ch]
'out ++ " "
]
print out
| 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: '))
|
Preserve the algorithm and functionality while converting the code from Arturo to VB. |
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": "----."
]
str: "hello world 2019"
out: ""
loop split str 'ch [
if not? whitespace? ch -> 'out ++ code\[ch]
'out ++ " "
]
print out
| 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
|
Change the following Arturo code into Go without altering its purpose. |
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": "----."
]
str: "hello world 2019"
out: ""
loop split str 'ch [
if not? whitespace? ch -> 'out ++ code\[ch]
'out ++ " "
]
print out
|
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 AutoHotKey implementation. | TestString := "Hello World! abcdefg @\
MorseBeep(teststring)
return
MorseBeep(passedString)
{
StringLower, passedString, passedString
Loop, Parse, passedString
morse .= A_LoopField = " " ? " " : A_LoopField = "a" ? ".- " : A_LoopField = "b" ? "-... " : A_LoopField = "c" ? "-.-. " : A_LoopField = "d" ? "-.. " : A_LoopField = "e" ? ". " : A_LoopField = "f" ? "..-. " : A_LoopField = "g" ? "--. " : A_LoopField = "h" ? ".... " : A_LoopField = "i" ? ".. " : A_LoopField = "j" ? ".--- " : A_LoopField = "k" ? "-.- " : A_LoopField = "l" ? ".-.. " : A_LoopField = "m" ? "-- " : A_LoopField = "n" ? "-. " : A_LoopField = "o" ? "--- " : A_LoopField = "p" ? ".--. " : A_LoopField = "q" ? "--.- " : A_LoopField = "r" ? ".-. " : A_LoopField = "s" ? "... " : A_LoopField = "t" ? "- " : A_LoopField = "u" ? "..- " : A_LoopField = "v" ? "...- " : A_LoopField = "w" ? ".-- " : A_LoopField = "x" ? "-..- " : A_LoopField = "y" ? "-.-- " : A_LoopField = "z" ? "--.. " : A_LoopField = "!" ? "---. " : A_LoopField = "\" ? ".-..-. " : A_LoopField = "$" ? "...-..- " : A_LoopField = "'" ? ".----. " : A_LoopField = "(" ? "-.--. " : A_LoopField = ")" ? "-.--.- " : A_LoopField = "+" ? ".-.-. " : A_LoopField = "," ? "--..-- " : A_LoopField = "-" ? "-....- " : A_LoopField = "." ? ".-.-.- " : A_LoopField = "/" ? "-..-. " : A_LoopField = "0" ? "----- " : A_LoopField = "1" ? ".---- " : A_LoopField = "2" ? "..--- " : A_LoopField = "3" ? "...-- " : A_LoopField = "4" ? "....- " : A_LoopField = "5" ? "..... " : A_LoopField = "6" ? "-.... " : A_LoopField = "7" ? "--... " : A_LoopField = "8" ? "---.. " : A_LoopField = "9" ? "----. " : A_LoopField = ":" ? "---... " : A_LoopField = "
Loop, Parse, morse
{
morsebeep := 120
if (A_LoopField = ".")
SoundBeep, 10*morsebeep, morsebeep
If (A_LoopField = "-")
SoundBeep, 10*morsebeep, 3*morsebeep
If (A_LoopField = " ")
Sleep, morsebeep
}
return 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;
}
|
Produce a language-to-language conversion: from AutoHotKey to C#, same semantics. | TestString := "Hello World! abcdefg @\
MorseBeep(teststring)
return
MorseBeep(passedString)
{
StringLower, passedString, passedString
Loop, Parse, passedString
morse .= A_LoopField = " " ? " " : A_LoopField = "a" ? ".- " : A_LoopField = "b" ? "-... " : A_LoopField = "c" ? "-.-. " : A_LoopField = "d" ? "-.. " : A_LoopField = "e" ? ". " : A_LoopField = "f" ? "..-. " : A_LoopField = "g" ? "--. " : A_LoopField = "h" ? ".... " : A_LoopField = "i" ? ".. " : A_LoopField = "j" ? ".--- " : A_LoopField = "k" ? "-.- " : A_LoopField = "l" ? ".-.. " : A_LoopField = "m" ? "-- " : A_LoopField = "n" ? "-. " : A_LoopField = "o" ? "--- " : A_LoopField = "p" ? ".--. " : A_LoopField = "q" ? "--.- " : A_LoopField = "r" ? ".-. " : A_LoopField = "s" ? "... " : A_LoopField = "t" ? "- " : A_LoopField = "u" ? "..- " : A_LoopField = "v" ? "...- " : A_LoopField = "w" ? ".-- " : A_LoopField = "x" ? "-..- " : A_LoopField = "y" ? "-.-- " : A_LoopField = "z" ? "--.. " : A_LoopField = "!" ? "---. " : A_LoopField = "\" ? ".-..-. " : A_LoopField = "$" ? "...-..- " : A_LoopField = "'" ? ".----. " : A_LoopField = "(" ? "-.--. " : A_LoopField = ")" ? "-.--.- " : A_LoopField = "+" ? ".-.-. " : A_LoopField = "," ? "--..-- " : A_LoopField = "-" ? "-....- " : A_LoopField = "." ? ".-.-.- " : A_LoopField = "/" ? "-..-. " : A_LoopField = "0" ? "----- " : A_LoopField = "1" ? ".---- " : A_LoopField = "2" ? "..--- " : A_LoopField = "3" ? "...-- " : A_LoopField = "4" ? "....- " : A_LoopField = "5" ? "..... " : A_LoopField = "6" ? "-.... " : A_LoopField = "7" ? "--... " : A_LoopField = "8" ? "---.. " : A_LoopField = "9" ? "----. " : A_LoopField = ":" ? "---... " : A_LoopField = "
Loop, Parse, morse
{
morsebeep := 120
if (A_LoopField = ".")
SoundBeep, 10*morsebeep, morsebeep
If (A_LoopField = "-")
SoundBeep, 10*morsebeep, 3*morsebeep
If (A_LoopField = " ")
Sleep, morsebeep
}
return 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);
}
}
}
}
|
Translate this program into Java but keep the logic exactly as in AutoHotKey. | TestString := "Hello World! abcdefg @\
MorseBeep(teststring)
return
MorseBeep(passedString)
{
StringLower, passedString, passedString
Loop, Parse, passedString
morse .= A_LoopField = " " ? " " : A_LoopField = "a" ? ".- " : A_LoopField = "b" ? "-... " : A_LoopField = "c" ? "-.-. " : A_LoopField = "d" ? "-.. " : A_LoopField = "e" ? ". " : A_LoopField = "f" ? "..-. " : A_LoopField = "g" ? "--. " : A_LoopField = "h" ? ".... " : A_LoopField = "i" ? ".. " : A_LoopField = "j" ? ".--- " : A_LoopField = "k" ? "-.- " : A_LoopField = "l" ? ".-.. " : A_LoopField = "m" ? "-- " : A_LoopField = "n" ? "-. " : A_LoopField = "o" ? "--- " : A_LoopField = "p" ? ".--. " : A_LoopField = "q" ? "--.- " : A_LoopField = "r" ? ".-. " : A_LoopField = "s" ? "... " : A_LoopField = "t" ? "- " : A_LoopField = "u" ? "..- " : A_LoopField = "v" ? "...- " : A_LoopField = "w" ? ".-- " : A_LoopField = "x" ? "-..- " : A_LoopField = "y" ? "-.-- " : A_LoopField = "z" ? "--.. " : A_LoopField = "!" ? "---. " : A_LoopField = "\" ? ".-..-. " : A_LoopField = "$" ? "...-..- " : A_LoopField = "'" ? ".----. " : A_LoopField = "(" ? "-.--. " : A_LoopField = ")" ? "-.--.- " : A_LoopField = "+" ? ".-.-. " : A_LoopField = "," ? "--..-- " : A_LoopField = "-" ? "-....- " : A_LoopField = "." ? ".-.-.- " : A_LoopField = "/" ? "-..-. " : A_LoopField = "0" ? "----- " : A_LoopField = "1" ? ".---- " : A_LoopField = "2" ? "..--- " : A_LoopField = "3" ? "...-- " : A_LoopField = "4" ? "....- " : A_LoopField = "5" ? "..... " : A_LoopField = "6" ? "-.... " : A_LoopField = "7" ? "--... " : A_LoopField = "8" ? "---.. " : A_LoopField = "9" ? "----. " : A_LoopField = ":" ? "---... " : A_LoopField = "
Loop, Parse, morse
{
morsebeep := 120
if (A_LoopField = ".")
SoundBeep, 10*morsebeep, morsebeep
If (A_LoopField = "-")
SoundBeep, 10*morsebeep, 3*morsebeep
If (A_LoopField = " ")
Sleep, morsebeep
}
return 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");
}
}
|
Produce a language-to-language conversion: from AutoHotKey to Python, same semantics. | TestString := "Hello World! abcdefg @\
MorseBeep(teststring)
return
MorseBeep(passedString)
{
StringLower, passedString, passedString
Loop, Parse, passedString
morse .= A_LoopField = " " ? " " : A_LoopField = "a" ? ".- " : A_LoopField = "b" ? "-... " : A_LoopField = "c" ? "-.-. " : A_LoopField = "d" ? "-.. " : A_LoopField = "e" ? ". " : A_LoopField = "f" ? "..-. " : A_LoopField = "g" ? "--. " : A_LoopField = "h" ? ".... " : A_LoopField = "i" ? ".. " : A_LoopField = "j" ? ".--- " : A_LoopField = "k" ? "-.- " : A_LoopField = "l" ? ".-.. " : A_LoopField = "m" ? "-- " : A_LoopField = "n" ? "-. " : A_LoopField = "o" ? "--- " : A_LoopField = "p" ? ".--. " : A_LoopField = "q" ? "--.- " : A_LoopField = "r" ? ".-. " : A_LoopField = "s" ? "... " : A_LoopField = "t" ? "- " : A_LoopField = "u" ? "..- " : A_LoopField = "v" ? "...- " : A_LoopField = "w" ? ".-- " : A_LoopField = "x" ? "-..- " : A_LoopField = "y" ? "-.-- " : A_LoopField = "z" ? "--.. " : A_LoopField = "!" ? "---. " : A_LoopField = "\" ? ".-..-. " : A_LoopField = "$" ? "...-..- " : A_LoopField = "'" ? ".----. " : A_LoopField = "(" ? "-.--. " : A_LoopField = ")" ? "-.--.- " : A_LoopField = "+" ? ".-.-. " : A_LoopField = "," ? "--..-- " : A_LoopField = "-" ? "-....- " : A_LoopField = "." ? ".-.-.- " : A_LoopField = "/" ? "-..-. " : A_LoopField = "0" ? "----- " : A_LoopField = "1" ? ".---- " : A_LoopField = "2" ? "..--- " : A_LoopField = "3" ? "...-- " : A_LoopField = "4" ? "....- " : A_LoopField = "5" ? "..... " : A_LoopField = "6" ? "-.... " : A_LoopField = "7" ? "--... " : A_LoopField = "8" ? "---.. " : A_LoopField = "9" ? "----. " : A_LoopField = ":" ? "---... " : A_LoopField = "
Loop, Parse, morse
{
morsebeep := 120
if (A_LoopField = ".")
SoundBeep, 10*morsebeep, morsebeep
If (A_LoopField = "-")
SoundBeep, 10*morsebeep, 3*morsebeep
If (A_LoopField = " ")
Sleep, morsebeep
}
return 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: '))
|
Produce a functionally identical VB code for the snippet given in AutoHotKey. | TestString := "Hello World! abcdefg @\
MorseBeep(teststring)
return
MorseBeep(passedString)
{
StringLower, passedString, passedString
Loop, Parse, passedString
morse .= A_LoopField = " " ? " " : A_LoopField = "a" ? ".- " : A_LoopField = "b" ? "-... " : A_LoopField = "c" ? "-.-. " : A_LoopField = "d" ? "-.. " : A_LoopField = "e" ? ". " : A_LoopField = "f" ? "..-. " : A_LoopField = "g" ? "--. " : A_LoopField = "h" ? ".... " : A_LoopField = "i" ? ".. " : A_LoopField = "j" ? ".--- " : A_LoopField = "k" ? "-.- " : A_LoopField = "l" ? ".-.. " : A_LoopField = "m" ? "-- " : A_LoopField = "n" ? "-. " : A_LoopField = "o" ? "--- " : A_LoopField = "p" ? ".--. " : A_LoopField = "q" ? "--.- " : A_LoopField = "r" ? ".-. " : A_LoopField = "s" ? "... " : A_LoopField = "t" ? "- " : A_LoopField = "u" ? "..- " : A_LoopField = "v" ? "...- " : A_LoopField = "w" ? ".-- " : A_LoopField = "x" ? "-..- " : A_LoopField = "y" ? "-.-- " : A_LoopField = "z" ? "--.. " : A_LoopField = "!" ? "---. " : A_LoopField = "\" ? ".-..-. " : A_LoopField = "$" ? "...-..- " : A_LoopField = "'" ? ".----. " : A_LoopField = "(" ? "-.--. " : A_LoopField = ")" ? "-.--.- " : A_LoopField = "+" ? ".-.-. " : A_LoopField = "," ? "--..-- " : A_LoopField = "-" ? "-....- " : A_LoopField = "." ? ".-.-.- " : A_LoopField = "/" ? "-..-. " : A_LoopField = "0" ? "----- " : A_LoopField = "1" ? ".---- " : A_LoopField = "2" ? "..--- " : A_LoopField = "3" ? "...-- " : A_LoopField = "4" ? "....- " : A_LoopField = "5" ? "..... " : A_LoopField = "6" ? "-.... " : A_LoopField = "7" ? "--... " : A_LoopField = "8" ? "---.. " : A_LoopField = "9" ? "----. " : A_LoopField = ":" ? "---... " : A_LoopField = "
Loop, Parse, morse
{
morsebeep := 120
if (A_LoopField = ".")
SoundBeep, 10*morsebeep, morsebeep
If (A_LoopField = "-")
SoundBeep, 10*morsebeep, 3*morsebeep
If (A_LoopField = " ")
Sleep, morsebeep
}
return 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
|
Produce a functionally identical Go code for the snippet given in AutoHotKey. | TestString := "Hello World! abcdefg @\
MorseBeep(teststring)
return
MorseBeep(passedString)
{
StringLower, passedString, passedString
Loop, Parse, passedString
morse .= A_LoopField = " " ? " " : A_LoopField = "a" ? ".- " : A_LoopField = "b" ? "-... " : A_LoopField = "c" ? "-.-. " : A_LoopField = "d" ? "-.. " : A_LoopField = "e" ? ". " : A_LoopField = "f" ? "..-. " : A_LoopField = "g" ? "--. " : A_LoopField = "h" ? ".... " : A_LoopField = "i" ? ".. " : A_LoopField = "j" ? ".--- " : A_LoopField = "k" ? "-.- " : A_LoopField = "l" ? ".-.. " : A_LoopField = "m" ? "-- " : A_LoopField = "n" ? "-. " : A_LoopField = "o" ? "--- " : A_LoopField = "p" ? ".--. " : A_LoopField = "q" ? "--.- " : A_LoopField = "r" ? ".-. " : A_LoopField = "s" ? "... " : A_LoopField = "t" ? "- " : A_LoopField = "u" ? "..- " : A_LoopField = "v" ? "...- " : A_LoopField = "w" ? ".-- " : A_LoopField = "x" ? "-..- " : A_LoopField = "y" ? "-.-- " : A_LoopField = "z" ? "--.. " : A_LoopField = "!" ? "---. " : A_LoopField = "\" ? ".-..-. " : A_LoopField = "$" ? "...-..- " : A_LoopField = "'" ? ".----. " : A_LoopField = "(" ? "-.--. " : A_LoopField = ")" ? "-.--.- " : A_LoopField = "+" ? ".-.-. " : A_LoopField = "," ? "--..-- " : A_LoopField = "-" ? "-....- " : A_LoopField = "." ? ".-.-.- " : A_LoopField = "/" ? "-..-. " : A_LoopField = "0" ? "----- " : A_LoopField = "1" ? ".---- " : A_LoopField = "2" ? "..--- " : A_LoopField = "3" ? "...-- " : A_LoopField = "4" ? "....- " : A_LoopField = "5" ? "..... " : A_LoopField = "6" ? "-.... " : A_LoopField = "7" ? "--... " : A_LoopField = "8" ? "---.. " : A_LoopField = "9" ? "----. " : A_LoopField = ":" ? "---... " : A_LoopField = "
Loop, Parse, morse
{
morsebeep := 120
if (A_LoopField = ".")
SoundBeep, 10*morsebeep, morsebeep
If (A_LoopField = "-")
SoundBeep, 10*morsebeep, 3*morsebeep
If (A_LoopField = " ")
Sleep, morsebeep
}
return 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
}
|
Change the programming language of this snippet from AWK to C without modifying what it does. |
BEGIN { FS="";
m="A.-B-...C-.-.D-..E.F..-.G--.H....I..J.---K-.-L.-..M--N-.";
m=m "O---P.--.Q--.-R.-.S...T-U..-V...-W.--X-..-Y-.--Z--.. ";
}
{ for(i=1; i<=NF; i++)
{
c=toupper($i); n=1; b=".";
while((c!=b)&&(b!=" ")) { b=substr(m,n,1); n++; }
b=substr(m,n,1);
while((b==".")||(b=="-")) { printf("%s",b); n++; b=substr(m,n,1); }
printf("|");
}
printf("\n");
}
|
#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;
}
|
Rewrite this program in C# while keeping its functionality equivalent to the AWK version. |
BEGIN { FS="";
m="A.-B-...C-.-.D-..E.F..-.G--.H....I..J.---K-.-L.-..M--N-.";
m=m "O---P.--.Q--.-R.-.S...T-U..-V...-W.--X-..-Y-.--Z--.. ";
}
{ for(i=1; i<=NF; i++)
{
c=toupper($i); n=1; b=".";
while((c!=b)&&(b!=" ")) { b=substr(m,n,1); n++; }
b=substr(m,n,1);
while((b==".")||(b=="-")) { printf("%s",b); n++; b=substr(m,n,1); }
printf("|");
}
printf("\n");
}
| 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 AWK to Java. |
BEGIN { FS="";
m="A.-B-...C-.-.D-..E.F..-.G--.H....I..J.---K-.-L.-..M--N-.";
m=m "O---P.--.Q--.-R.-.S...T-U..-V...-W.--X-..-Y-.--Z--.. ";
}
{ for(i=1; i<=NF; i++)
{
c=toupper($i); n=1; b=".";
while((c!=b)&&(b!=" ")) { b=substr(m,n,1); n++; }
b=substr(m,n,1);
while((b==".")||(b=="-")) { printf("%s",b); n++; b=substr(m,n,1); }
printf("|");
}
printf("\n");
}
| 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 AWK code snippet into Python without altering its behavior. |
BEGIN { FS="";
m="A.-B-...C-.-.D-..E.F..-.G--.H....I..J.---K-.-L.-..M--N-.";
m=m "O---P.--.Q--.-R.-.S...T-U..-V...-W.--X-..-Y-.--Z--.. ";
}
{ for(i=1; i<=NF; i++)
{
c=toupper($i); n=1; b=".";
while((c!=b)&&(b!=" ")) { b=substr(m,n,1); n++; }
b=substr(m,n,1);
while((b==".")||(b=="-")) { printf("%s",b); n++; b=substr(m,n,1); }
printf("|");
}
printf("\n");
}
| 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: '))
|
Produce a functionally identical VB code for the snippet given in AWK. |
BEGIN { FS="";
m="A.-B-...C-.-.D-..E.F..-.G--.H....I..J.---K-.-L.-..M--N-.";
m=m "O---P.--.Q--.-R.-.S...T-U..-V...-W.--X-..-Y-.--Z--.. ";
}
{ for(i=1; i<=NF; i++)
{
c=toupper($i); n=1; b=".";
while((c!=b)&&(b!=" ")) { b=substr(m,n,1); n++; }
b=substr(m,n,1);
while((b==".")||(b=="-")) { printf("%s",b); n++; b=substr(m,n,1); }
printf("|");
}
printf("\n");
}
| 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
|
Keep all operations the same but rewrite the snippet in Go. |
BEGIN { FS="";
m="A.-B-...C-.-.D-..E.F..-.G--.H....I..J.---K-.-L.-..M--N-.";
m=m "O---P.--.Q--.-R.-.S...T-U..-V...-W.--X-..-Y-.--Z--.. ";
}
{ for(i=1; i<=NF; i++)
{
c=toupper($i); n=1; b=".";
while((c!=b)&&(b!=" ")) { b=substr(m,n,1); n++; }
b=substr(m,n,1);
while((b==".")||(b=="-")) { printf("%s",b); n++; b=substr(m,n,1); }
printf("|");
}
printf("\n");
}
|
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 BBC_Basic snippet without changing its computational steps. | *TEMPO 8
DIM morse$(63)
FOR char% = 0 TO 63 : READ morse$(char%) : NEXT char%
PROCmorse("The five boxing wizards jump quickly.")
END
DEF PROCmorse(text$)
LOCAL element%, index%, char&, morse$
FOR index% = 1 TO LEN(text$)
char& = ASC(MID$(text$,index%)) AND &7F
IF char& < 32 char& = 32
IF char& > 95 char& -= 32
morse$ = morse$(char&-32)
FOR element% = 1 TO LEN(morse$)
SOUND 1, -15, 148, VAL(MID$(morse$,element%,1))
SOUND 1, -15, 0, 1
NEXT element%
SOUND 1, -15, 0, 2
NEXT index%
ENDPROC
DATA 00,313133,131131,6,1113113,6,13111,133331,31331,313313,6,13131,331133,311113,131313,31131
DATA 33333,13333,11333,11133,11113,11111,31111,33111,33311,33331,333111,313131,6,31113,6,113311
DATA 133131,13,3111,3131,311,1,1131,331,1111,11,1333,313,1311,33,31,333
DATA 1331,3313,131,111,3,113,1113,133,3113,3133,3311,6,6,6,6,113313
|
#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 BBC_Basic. | *TEMPO 8
DIM morse$(63)
FOR char% = 0 TO 63 : READ morse$(char%) : NEXT char%
PROCmorse("The five boxing wizards jump quickly.")
END
DEF PROCmorse(text$)
LOCAL element%, index%, char&, morse$
FOR index% = 1 TO LEN(text$)
char& = ASC(MID$(text$,index%)) AND &7F
IF char& < 32 char& = 32
IF char& > 95 char& -= 32
morse$ = morse$(char&-32)
FOR element% = 1 TO LEN(morse$)
SOUND 1, -15, 148, VAL(MID$(morse$,element%,1))
SOUND 1, -15, 0, 1
NEXT element%
SOUND 1, -15, 0, 2
NEXT index%
ENDPROC
DATA 00,313133,131131,6,1113113,6,13111,133331,31331,313313,6,13131,331133,311113,131313,31131
DATA 33333,13333,11333,11133,11113,11111,31111,33111,33311,33331,333111,313131,6,31113,6,113311
DATA 133131,13,3111,3131,311,1,1131,331,1111,11,1333,313,1311,33,31,333
DATA 1331,3313,131,111,3,113,1113,133,3113,3133,3311,6,6,6,6,113313
| 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 BBC_Basic code into Java without altering its purpose. | *TEMPO 8
DIM morse$(63)
FOR char% = 0 TO 63 : READ morse$(char%) : NEXT char%
PROCmorse("The five boxing wizards jump quickly.")
END
DEF PROCmorse(text$)
LOCAL element%, index%, char&, morse$
FOR index% = 1 TO LEN(text$)
char& = ASC(MID$(text$,index%)) AND &7F
IF char& < 32 char& = 32
IF char& > 95 char& -= 32
morse$ = morse$(char&-32)
FOR element% = 1 TO LEN(morse$)
SOUND 1, -15, 148, VAL(MID$(morse$,element%,1))
SOUND 1, -15, 0, 1
NEXT element%
SOUND 1, -15, 0, 2
NEXT index%
ENDPROC
DATA 00,313133,131131,6,1113113,6,13111,133331,31331,313313,6,13131,331133,311113,131313,31131
DATA 33333,13333,11333,11133,11113,11111,31111,33111,33311,33331,333111,313131,6,31113,6,113311
DATA 133131,13,3111,3131,311,1,1131,331,1111,11,1333,313,1311,33,31,333
DATA 1331,3313,131,111,3,113,1113,133,3113,3133,3311,6,6,6,6,113313
| 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");
}
}
|
Maintain the same structure and functionality when rewriting this code in Python. | *TEMPO 8
DIM morse$(63)
FOR char% = 0 TO 63 : READ morse$(char%) : NEXT char%
PROCmorse("The five boxing wizards jump quickly.")
END
DEF PROCmorse(text$)
LOCAL element%, index%, char&, morse$
FOR index% = 1 TO LEN(text$)
char& = ASC(MID$(text$,index%)) AND &7F
IF char& < 32 char& = 32
IF char& > 95 char& -= 32
morse$ = morse$(char&-32)
FOR element% = 1 TO LEN(morse$)
SOUND 1, -15, 148, VAL(MID$(morse$,element%,1))
SOUND 1, -15, 0, 1
NEXT element%
SOUND 1, -15, 0, 2
NEXT index%
ENDPROC
DATA 00,313133,131131,6,1113113,6,13111,133331,31331,313313,6,13131,331133,311113,131313,31131
DATA 33333,13333,11333,11133,11113,11111,31111,33111,33311,33331,333111,313131,6,31113,6,113311
DATA 133131,13,3111,3131,311,1,1131,331,1111,11,1333,313,1311,33,31,333
DATA 1331,3313,131,111,3,113,1113,133,3113,3133,3311,6,6,6,6,113313
| 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 BBC_Basic to VB, ensuring the logic remains intact. | *TEMPO 8
DIM morse$(63)
FOR char% = 0 TO 63 : READ morse$(char%) : NEXT char%
PROCmorse("The five boxing wizards jump quickly.")
END
DEF PROCmorse(text$)
LOCAL element%, index%, char&, morse$
FOR index% = 1 TO LEN(text$)
char& = ASC(MID$(text$,index%)) AND &7F
IF char& < 32 char& = 32
IF char& > 95 char& -= 32
morse$ = morse$(char&-32)
FOR element% = 1 TO LEN(morse$)
SOUND 1, -15, 148, VAL(MID$(morse$,element%,1))
SOUND 1, -15, 0, 1
NEXT element%
SOUND 1, -15, 0, 2
NEXT index%
ENDPROC
DATA 00,313133,131131,6,1113113,6,13111,133331,31331,313313,6,13131,331133,311113,131313,31131
DATA 33333,13333,11333,11133,11113,11111,31111,33111,33311,33331,333111,313131,6,31113,6,113311
DATA 133131,13,3111,3131,311,1,1131,331,1111,11,1333,313,1311,33,31,333
DATA 1331,3313,131,111,3,113,1113,133,3113,3133,3311,6,6,6,6,113313
| 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
|
Produce a functionally identical Go code for the snippet given in BBC_Basic. | *TEMPO 8
DIM morse$(63)
FOR char% = 0 TO 63 : READ morse$(char%) : NEXT char%
PROCmorse("The five boxing wizards jump quickly.")
END
DEF PROCmorse(text$)
LOCAL element%, index%, char&, morse$
FOR index% = 1 TO LEN(text$)
char& = ASC(MID$(text$,index%)) AND &7F
IF char& < 32 char& = 32
IF char& > 95 char& -= 32
morse$ = morse$(char&-32)
FOR element% = 1 TO LEN(morse$)
SOUND 1, -15, 148, VAL(MID$(morse$,element%,1))
SOUND 1, -15, 0, 1
NEXT element%
SOUND 1, -15, 0, 2
NEXT index%
ENDPROC
DATA 00,313133,131131,6,1113113,6,13111,133331,31331,313313,6,13131,331133,311113,131313,31131
DATA 33333,13333,11333,11133,11113,11111,31111,33111,33311,33331,333111,313131,6,31113,6,113311
DATA 133131,13,3111,3131,311,1,1131,331,1111,11,1333,313,1311,33,31,333
DATA 1331,3313,131,111,3,113,1113,133,3113,3133,3311,6,6,6,6,113313
|
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 programming language of this snippet from Clojure to C without modifying what it does. | (import [javax.sound.sampled AudioFormat AudioSystem SourceDataLine])
(defn play [sample-rate bs]
(let [af (AudioFormat. sample-rate 8 1 true true)]
(doto (AudioSystem/getSourceDataLine af)
(.open af sample-rate)
.start
(.write bs 0 (count bs))
.drain
.close)))
(defn note [hz sample-rate ms]
(let [period (/ hz sample-rate)]
(->> (range (* sample-rate ms 1/1000))
(map #(->> (* 2 Math/PI % period)
Math/sin
(* 127 ,)
byte) ,))))
(def morse-codes
{\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 "----." \& ".-..." \@ ".--.-."
\space " "})
(def sample-rate 1024)
(let [hz 440
ms 50]
(def sounds
{\. (note hz sample-rate (* 1 ms))
\- (note hz sample-rate(* 3 ms))
:element-gap (note 0 sample-rate (* 1 ms))
:letter-gap (note 0 sample-rate (* 3 ms))
\space (note 0 sample-rate (* 1 ms))}))
(defn convert-letter [letter]
(->> (get morse-codes letter "")
(map sounds ,)
(interpose (:element-gap sounds) ,)
(apply concat ,)))
(defn morse [s]
(->> (.toUpperCase s)
(map convert-letter ,)
(interpose (:letter-gap sounds) ,)
(apply concat ,)
byte-array
(play sample-rate ,)))
|
#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;
}
|
Ensure the translated C# code behaves exactly like the original Clojure snippet. | (import [javax.sound.sampled AudioFormat AudioSystem SourceDataLine])
(defn play [sample-rate bs]
(let [af (AudioFormat. sample-rate 8 1 true true)]
(doto (AudioSystem/getSourceDataLine af)
(.open af sample-rate)
.start
(.write bs 0 (count bs))
.drain
.close)))
(defn note [hz sample-rate ms]
(let [period (/ hz sample-rate)]
(->> (range (* sample-rate ms 1/1000))
(map #(->> (* 2 Math/PI % period)
Math/sin
(* 127 ,)
byte) ,))))
(def morse-codes
{\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 "----." \& ".-..." \@ ".--.-."
\space " "})
(def sample-rate 1024)
(let [hz 440
ms 50]
(def sounds
{\. (note hz sample-rate (* 1 ms))
\- (note hz sample-rate(* 3 ms))
:element-gap (note 0 sample-rate (* 1 ms))
:letter-gap (note 0 sample-rate (* 3 ms))
\space (note 0 sample-rate (* 1 ms))}))
(defn convert-letter [letter]
(->> (get morse-codes letter "")
(map sounds ,)
(interpose (:element-gap sounds) ,)
(apply concat ,)))
(defn morse [s]
(->> (.toUpperCase s)
(map convert-letter ,)
(interpose (:letter-gap sounds) ,)
(apply concat ,)
byte-array
(play sample-rate ,)))
| 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 provided Clojure code into Java while preserving the original functionality. | (import [javax.sound.sampled AudioFormat AudioSystem SourceDataLine])
(defn play [sample-rate bs]
(let [af (AudioFormat. sample-rate 8 1 true true)]
(doto (AudioSystem/getSourceDataLine af)
(.open af sample-rate)
.start
(.write bs 0 (count bs))
.drain
.close)))
(defn note [hz sample-rate ms]
(let [period (/ hz sample-rate)]
(->> (range (* sample-rate ms 1/1000))
(map #(->> (* 2 Math/PI % period)
Math/sin
(* 127 ,)
byte) ,))))
(def morse-codes
{\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 "----." \& ".-..." \@ ".--.-."
\space " "})
(def sample-rate 1024)
(let [hz 440
ms 50]
(def sounds
{\. (note hz sample-rate (* 1 ms))
\- (note hz sample-rate(* 3 ms))
:element-gap (note 0 sample-rate (* 1 ms))
:letter-gap (note 0 sample-rate (* 3 ms))
\space (note 0 sample-rate (* 1 ms))}))
(defn convert-letter [letter]
(->> (get morse-codes letter "")
(map sounds ,)
(interpose (:element-gap sounds) ,)
(apply concat ,)))
(defn morse [s]
(->> (.toUpperCase s)
(map convert-letter ,)
(interpose (:letter-gap sounds) ,)
(apply concat ,)
byte-array
(play sample-rate ,)))
| 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 algorithm in Python as shown in this Clojure implementation. | (import [javax.sound.sampled AudioFormat AudioSystem SourceDataLine])
(defn play [sample-rate bs]
(let [af (AudioFormat. sample-rate 8 1 true true)]
(doto (AudioSystem/getSourceDataLine af)
(.open af sample-rate)
.start
(.write bs 0 (count bs))
.drain
.close)))
(defn note [hz sample-rate ms]
(let [period (/ hz sample-rate)]
(->> (range (* sample-rate ms 1/1000))
(map #(->> (* 2 Math/PI % period)
Math/sin
(* 127 ,)
byte) ,))))
(def morse-codes
{\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 "----." \& ".-..." \@ ".--.-."
\space " "})
(def sample-rate 1024)
(let [hz 440
ms 50]
(def sounds
{\. (note hz sample-rate (* 1 ms))
\- (note hz sample-rate(* 3 ms))
:element-gap (note 0 sample-rate (* 1 ms))
:letter-gap (note 0 sample-rate (* 3 ms))
\space (note 0 sample-rate (* 1 ms))}))
(defn convert-letter [letter]
(->> (get morse-codes letter "")
(map sounds ,)
(interpose (:element-gap sounds) ,)
(apply concat ,)))
(defn morse [s]
(->> (.toUpperCase s)
(map convert-letter ,)
(interpose (:letter-gap sounds) ,)
(apply concat ,)
byte-array
(play sample-rate ,)))
| 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 Clojure snippet. | (import [javax.sound.sampled AudioFormat AudioSystem SourceDataLine])
(defn play [sample-rate bs]
(let [af (AudioFormat. sample-rate 8 1 true true)]
(doto (AudioSystem/getSourceDataLine af)
(.open af sample-rate)
.start
(.write bs 0 (count bs))
.drain
.close)))
(defn note [hz sample-rate ms]
(let [period (/ hz sample-rate)]
(->> (range (* sample-rate ms 1/1000))
(map #(->> (* 2 Math/PI % period)
Math/sin
(* 127 ,)
byte) ,))))
(def morse-codes
{\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 "----." \& ".-..." \@ ".--.-."
\space " "})
(def sample-rate 1024)
(let [hz 440
ms 50]
(def sounds
{\. (note hz sample-rate (* 1 ms))
\- (note hz sample-rate(* 3 ms))
:element-gap (note 0 sample-rate (* 1 ms))
:letter-gap (note 0 sample-rate (* 3 ms))
\space (note 0 sample-rate (* 1 ms))}))
(defn convert-letter [letter]
(->> (get morse-codes letter "")
(map sounds ,)
(interpose (:element-gap sounds) ,)
(apply concat ,)))
(defn morse [s]
(->> (.toUpperCase s)
(map convert-letter ,)
(interpose (:letter-gap sounds) ,)
(apply concat ,)
byte-array
(play sample-rate ,)))
| 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
|
Preserve the algorithm and functionality while converting the code from Clojure to Go. | (import [javax.sound.sampled AudioFormat AudioSystem SourceDataLine])
(defn play [sample-rate bs]
(let [af (AudioFormat. sample-rate 8 1 true true)]
(doto (AudioSystem/getSourceDataLine af)
(.open af sample-rate)
.start
(.write bs 0 (count bs))
.drain
.close)))
(defn note [hz sample-rate ms]
(let [period (/ hz sample-rate)]
(->> (range (* sample-rate ms 1/1000))
(map #(->> (* 2 Math/PI % period)
Math/sin
(* 127 ,)
byte) ,))))
(def morse-codes
{\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 "----." \& ".-..." \@ ".--.-."
\space " "})
(def sample-rate 1024)
(let [hz 440
ms 50]
(def sounds
{\. (note hz sample-rate (* 1 ms))
\- (note hz sample-rate(* 3 ms))
:element-gap (note 0 sample-rate (* 1 ms))
:letter-gap (note 0 sample-rate (* 3 ms))
\space (note 0 sample-rate (* 1 ms))}))
(defn convert-letter [letter]
(->> (get morse-codes letter "")
(map sounds ,)
(interpose (:element-gap sounds) ,)
(apply concat ,)))
(defn morse [s]
(->> (.toUpperCase s)
(map convert-letter ,)
(interpose (:letter-gap sounds) ,)
(apply concat ,)
byte-array
(play sample-rate ,)))
|
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
}
|
Rewrite this program in C while keeping its functionality equivalent to the D version. | import std.conv;
import std.stdio;
immutable string[char] morsecode;
static this() {
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': "----."
];
}
void main(string[] args) {
foreach (arg; args[1..$]) {
writeln(arg);
foreach (ch; arg) {
if (ch in morsecode) {
write(morsecode[ch]);
}
write(' ');
}
writeln();
}
}
|
#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;
}
|
Generate a C# translation of this D snippet without changing its computational steps. | import std.conv;
import std.stdio;
immutable string[char] morsecode;
static this() {
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': "----."
];
}
void main(string[] args) {
foreach (arg; args[1..$]) {
writeln(arg);
foreach (ch; arg) {
if (ch in morsecode) {
write(morsecode[ch]);
}
write(' ');
}
writeln();
}
}
| 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 this program into Java but keep the logic exactly as in D. | import std.conv;
import std.stdio;
immutable string[char] morsecode;
static this() {
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': "----."
];
}
void main(string[] args) {
foreach (arg; args[1..$]) {
writeln(arg);
foreach (ch; arg) {
if (ch in morsecode) {
write(morsecode[ch]);
}
write(' ');
}
writeln();
}
}
| 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 D to Python with equivalent syntax and logic. | import std.conv;
import std.stdio;
immutable string[char] morsecode;
static this() {
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': "----."
];
}
void main(string[] args) {
foreach (arg; args[1..$]) {
writeln(arg);
foreach (ch; arg) {
if (ch in morsecode) {
write(morsecode[ch]);
}
write(' ');
}
writeln();
}
}
| 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: '))
|
Preserve the algorithm and functionality while converting the code from D to VB. | import std.conv;
import std.stdio;
immutable string[char] morsecode;
static this() {
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': "----."
];
}
void main(string[] args) {
foreach (arg; args[1..$]) {
writeln(arg);
foreach (ch; arg) {
if (ch in morsecode) {
write(morsecode[ch]);
}
write(' ');
}
writeln();
}
}
| 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
|
Preserve the algorithm and functionality while converting the code from D to Go. | import std.conv;
import std.stdio;
immutable string[char] morsecode;
static this() {
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': "----."
];
}
void main(string[] args) {
foreach (arg; args[1..$]) {
writeln(arg);
foreach (ch; arg) {
if (ch in morsecode) {
write(morsecode[ch]);
}
write(' ');
}
writeln();
}
}
|
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 Delphi code into C without altering its purpose. | program Morse;
uses
System.Generics.Collections,
SysUtils,
Windows;
const
Codes: array[0..35, 0..1] of 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', '----.'));
var
Dictionary: TDictionary<String, String>;
procedure InitCodes;
var
i: Integer;
begin
for i := 0 to High(Codes) do
Dictionary.Add(Codes[i, 0], Codes[i, 1]);
end;
procedure SayMorse(const Word: String);
var
s: String;
begin
for s in Word do
if s = '.' then
Windows.Beep(1000, 250)
else if s = '-' then
Windows.Beep(1000, 750)
else
Windows.Beep(1000, 1000);
end;
procedure ParseMorse(const Word: String);
var
s, Value: String;
begin
for s in word do
if Dictionary.TryGetValue(s, Value) then
begin
Write(Value + ' ');
SayMorse(Value);
end;
end;
begin
Dictionary := TDictionary<String, String>.Create;
try
InitCodes;
if ParamCount = 0 then
ParseMorse('sos')
else if ParamCount = 1 then
ParseMorse(LowerCase(ParamStr(1)))
else
Writeln('Usage: Morse.exe anyword');
Readln;
finally
Dictionary.Free;
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;
}
|
Generate an equivalent C# version of this Delphi code. | program Morse;
uses
System.Generics.Collections,
SysUtils,
Windows;
const
Codes: array[0..35, 0..1] of 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', '----.'));
var
Dictionary: TDictionary<String, String>;
procedure InitCodes;
var
i: Integer;
begin
for i := 0 to High(Codes) do
Dictionary.Add(Codes[i, 0], Codes[i, 1]);
end;
procedure SayMorse(const Word: String);
var
s: String;
begin
for s in Word do
if s = '.' then
Windows.Beep(1000, 250)
else if s = '-' then
Windows.Beep(1000, 750)
else
Windows.Beep(1000, 1000);
end;
procedure ParseMorse(const Word: String);
var
s, Value: String;
begin
for s in word do
if Dictionary.TryGetValue(s, Value) then
begin
Write(Value + ' ');
SayMorse(Value);
end;
end;
begin
Dictionary := TDictionary<String, String>.Create;
try
InitCodes;
if ParamCount = 0 then
ParseMorse('sos')
else if ParamCount = 1 then
ParseMorse(LowerCase(ParamStr(1)))
else
Writeln('Usage: Morse.exe anyword');
Readln;
finally
Dictionary.Free;
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);
}
}
}
}
|
Convert this Delphi snippet to Java and keep its semantics consistent. | program Morse;
uses
System.Generics.Collections,
SysUtils,
Windows;
const
Codes: array[0..35, 0..1] of 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', '----.'));
var
Dictionary: TDictionary<String, String>;
procedure InitCodes;
var
i: Integer;
begin
for i := 0 to High(Codes) do
Dictionary.Add(Codes[i, 0], Codes[i, 1]);
end;
procedure SayMorse(const Word: String);
var
s: String;
begin
for s in Word do
if s = '.' then
Windows.Beep(1000, 250)
else if s = '-' then
Windows.Beep(1000, 750)
else
Windows.Beep(1000, 1000);
end;
procedure ParseMorse(const Word: String);
var
s, Value: String;
begin
for s in word do
if Dictionary.TryGetValue(s, Value) then
begin
Write(Value + ' ');
SayMorse(Value);
end;
end;
begin
Dictionary := TDictionary<String, String>.Create;
try
InitCodes;
if ParamCount = 0 then
ParseMorse('sos')
else if ParamCount = 1 then
ParseMorse(LowerCase(ParamStr(1)))
else
Writeln('Usage: Morse.exe anyword');
Readln;
finally
Dictionary.Free;
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");
}
}
|
Generate an equivalent Python version of this Delphi code. | program Morse;
uses
System.Generics.Collections,
SysUtils,
Windows;
const
Codes: array[0..35, 0..1] of 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', '----.'));
var
Dictionary: TDictionary<String, String>;
procedure InitCodes;
var
i: Integer;
begin
for i := 0 to High(Codes) do
Dictionary.Add(Codes[i, 0], Codes[i, 1]);
end;
procedure SayMorse(const Word: String);
var
s: String;
begin
for s in Word do
if s = '.' then
Windows.Beep(1000, 250)
else if s = '-' then
Windows.Beep(1000, 750)
else
Windows.Beep(1000, 1000);
end;
procedure ParseMorse(const Word: String);
var
s, Value: String;
begin
for s in word do
if Dictionary.TryGetValue(s, Value) then
begin
Write(Value + ' ');
SayMorse(Value);
end;
end;
begin
Dictionary := TDictionary<String, String>.Create;
try
InitCodes;
if ParamCount = 0 then
ParseMorse('sos')
else if ParamCount = 1 then
ParseMorse(LowerCase(ParamStr(1)))
else
Writeln('Usage: Morse.exe anyword');
Readln;
finally
Dictionary.Free;
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: '))
|
Port the provided Delphi code into VB while preserving the original functionality. | program Morse;
uses
System.Generics.Collections,
SysUtils,
Windows;
const
Codes: array[0..35, 0..1] of 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', '----.'));
var
Dictionary: TDictionary<String, String>;
procedure InitCodes;
var
i: Integer;
begin
for i := 0 to High(Codes) do
Dictionary.Add(Codes[i, 0], Codes[i, 1]);
end;
procedure SayMorse(const Word: String);
var
s: String;
begin
for s in Word do
if s = '.' then
Windows.Beep(1000, 250)
else if s = '-' then
Windows.Beep(1000, 750)
else
Windows.Beep(1000, 1000);
end;
procedure ParseMorse(const Word: String);
var
s, Value: String;
begin
for s in word do
if Dictionary.TryGetValue(s, Value) then
begin
Write(Value + ' ');
SayMorse(Value);
end;
end;
begin
Dictionary := TDictionary<String, String>.Create;
try
InitCodes;
if ParamCount = 0 then
ParseMorse('sos')
else if ParamCount = 1 then
ParseMorse(LowerCase(ParamStr(1)))
else
Writeln('Usage: Morse.exe anyword');
Readln;
finally
Dictionary.Free;
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 this program in Go while keeping its functionality equivalent to the Delphi version. | program Morse;
uses
System.Generics.Collections,
SysUtils,
Windows;
const
Codes: array[0..35, 0..1] of 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', '----.'));
var
Dictionary: TDictionary<String, String>;
procedure InitCodes;
var
i: Integer;
begin
for i := 0 to High(Codes) do
Dictionary.Add(Codes[i, 0], Codes[i, 1]);
end;
procedure SayMorse(const Word: String);
var
s: String;
begin
for s in Word do
if s = '.' then
Windows.Beep(1000, 250)
else if s = '-' then
Windows.Beep(1000, 750)
else
Windows.Beep(1000, 1000);
end;
procedure ParseMorse(const Word: String);
var
s, Value: String;
begin
for s in word do
if Dictionary.TryGetValue(s, Value) then
begin
Write(Value + ' ');
SayMorse(Value);
end;
end;
begin
Dictionary := TDictionary<String, String>.Create;
try
InitCodes;
if ParamCount = 0 then
ParseMorse('sos')
else if ParamCount = 1 then
ParseMorse(LowerCase(ParamStr(1)))
else
Writeln('Usage: Morse.exe anyword');
Readln;
finally
Dictionary.Free;
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
}
|
Port the provided Elixir code into C while preserving the original functionality. | defmodule Morse do
@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" => "--..",
"[" => "-.--.", "]" => "-.--.-", "_" => "..--.-" }
def code(text) do
String.upcase(text)
|> String.codepoints
|> Enum.map_join(" ", fn c -> Map.get(@morse, c, " ") end)
end
end
IO.puts Morse.code("Hello, World!")
|
#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 Elixir to C#. | defmodule Morse do
@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" => "--..",
"[" => "-.--.", "]" => "-.--.-", "_" => "..--.-" }
def code(text) do
String.upcase(text)
|> String.codepoints
|> Enum.map_join(" ", fn c -> Map.get(@morse, c, " ") end)
end
end
IO.puts Morse.code("Hello, World!")
| 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 Elixir. | defmodule Morse do
@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" => "--..",
"[" => "-.--.", "]" => "-.--.-", "_" => "..--.-" }
def code(text) do
String.upcase(text)
|> String.codepoints
|> Enum.map_join(" ", fn c -> Map.get(@morse, c, " ") end)
end
end
IO.puts Morse.code("Hello, World!")
| 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");
}
}
|
Change the following Elixir code into Python without altering its purpose. | defmodule Morse do
@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" => "--..",
"[" => "-.--.", "]" => "-.--.-", "_" => "..--.-" }
def code(text) do
String.upcase(text)
|> String.codepoints
|> Enum.map_join(" ", fn c -> Map.get(@morse, c, " ") end)
end
end
IO.puts Morse.code("Hello, World!")
| 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 Elixir code snippet into VB without altering its behavior. | defmodule Morse do
@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" => "--..",
"[" => "-.--.", "]" => "-.--.-", "_" => "..--.-" }
def code(text) do
String.upcase(text)
|> String.codepoints
|> Enum.map_join(" ", fn c -> Map.get(@morse, c, " ") end)
end
end
IO.puts Morse.code("Hello, World!")
| 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 Elixir snippet without changing its computational steps. | defmodule Morse do
@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" => "--..",
"[" => "-.--.", "]" => "-.--.-", "_" => "..--.-" }
def code(text) do
String.upcase(text)
|> String.codepoints
|> Enum.map_join(" ", fn c -> Map.get(@morse, c, " ") end)
end
end
IO.puts Morse.code("Hello, World!")
|
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
}
|
Port the provided F# code into C while preserving the original functionality. | open System
open System.Threading
let morse = Map.ofList
[('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 beep c =
match c with
| '.' ->
printf "."
Console.Beep(1200, 250)
| '_' ->
printf "_"
Console.Beep(1200, 1000)
| _ ->
printf " "
Thread.Sleep(125)
let trim (s: string) = s.Trim()
let toMorse c = Map.find c morse
let lower (s: string) = s.ToLower()
let sanitize = String.filter Char.IsLetterOrDigit
let send = sanitize >> lower >> String.collect toMorse >> trim >> String.iter beep
send "Rosetta Code"
|
#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#. | open System
open System.Threading
let morse = Map.ofList
[('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 beep c =
match c with
| '.' ->
printf "."
Console.Beep(1200, 250)
| '_' ->
printf "_"
Console.Beep(1200, 1000)
| _ ->
printf " "
Thread.Sleep(125)
let trim (s: string) = s.Trim()
let toMorse c = Map.find c morse
let lower (s: string) = s.ToLower()
let sanitize = String.filter Char.IsLetterOrDigit
let send = sanitize >> lower >> String.collect toMorse >> trim >> String.iter beep
send "Rosetta Code"
| 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 F# to Java. | open System
open System.Threading
let morse = Map.ofList
[('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 beep c =
match c with
| '.' ->
printf "."
Console.Beep(1200, 250)
| '_' ->
printf "_"
Console.Beep(1200, 1000)
| _ ->
printf " "
Thread.Sleep(125)
let trim (s: string) = s.Trim()
let toMorse c = Map.find c morse
let lower (s: string) = s.ToLower()
let sanitize = String.filter Char.IsLetterOrDigit
let send = sanitize >> lower >> String.collect toMorse >> trim >> String.iter beep
send "Rosetta Code"
| 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");
}
}
|
Change the following F# code into Python without altering its purpose. | open System
open System.Threading
let morse = Map.ofList
[('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 beep c =
match c with
| '.' ->
printf "."
Console.Beep(1200, 250)
| '_' ->
printf "_"
Console.Beep(1200, 1000)
| _ ->
printf " "
Thread.Sleep(125)
let trim (s: string) = s.Trim()
let toMorse c = Map.find c morse
let lower (s: string) = s.ToLower()
let sanitize = String.filter Char.IsLetterOrDigit
let send = sanitize >> lower >> String.collect toMorse >> trim >> String.iter beep
send "Rosetta Code"
| 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 F# code into VB without altering its purpose. | open System
open System.Threading
let morse = Map.ofList
[('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 beep c =
match c with
| '.' ->
printf "."
Console.Beep(1200, 250)
| '_' ->
printf "_"
Console.Beep(1200, 1000)
| _ ->
printf " "
Thread.Sleep(125)
let trim (s: string) = s.Trim()
let toMorse c = Map.find c morse
let lower (s: string) = s.ToLower()
let sanitize = String.filter Char.IsLetterOrDigit
let send = sanitize >> lower >> String.collect toMorse >> trim >> String.iter beep
send "Rosetta Code"
| 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
|
Convert this F# snippet to Go and keep its semantics consistent. | open System
open System.Threading
let morse = Map.ofList
[('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 beep c =
match c with
| '.' ->
printf "."
Console.Beep(1200, 250)
| '_' ->
printf "_"
Console.Beep(1200, 1000)
| _ ->
printf " "
Thread.Sleep(125)
let trim (s: string) = s.Trim()
let toMorse c = Map.find c morse
let lower (s: string) = s.ToLower()
let sanitize = String.filter Char.IsLetterOrDigit
let send = sanitize >> lower >> String.collect toMorse >> trim >> String.iter beep
send "Rosetta Code"
|
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 Factor implementation into C, maintaining the same output and logic. | USE: morse
"Hello world
|
#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;
}
|
Keep all operations the same but rewrite the snippet in C#. | USE: morse
"Hello world
| 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. | USE: morse
"Hello world
| 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 provided Factor code into Python while preserving the original functionality. | USE: morse
"Hello world
| 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 this Factor snippet to VB and keep its semantics consistent. | USE: morse
"Hello world
| 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 Factor code snippet into Go without altering its behavior. | USE: morse
"Hello world
|
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 Haskell to C, ensuring the logic remains intact. | import System.IO
import MorseCode
import MorsePlaySox
main = do
hSetBuffering stdin NoBuffering
text <- getContents
play $ toMorse text
|
#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 Haskell code in C#. | import System.IO
import MorseCode
import MorsePlaySox
main = do
hSetBuffering stdin NoBuffering
text <- getContents
play $ toMorse text
| 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 programming language of this snippet from Haskell to Java without modifying what it does. | import System.IO
import MorseCode
import MorsePlaySox
main = do
hSetBuffering stdin NoBuffering
text <- getContents
play $ toMorse text
| 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 Haskell, keeping it the same logically? | import System.IO
import MorseCode
import MorsePlaySox
main = do
hSetBuffering stdin NoBuffering
text <- getContents
play $ toMorse text
| 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 this Haskell snippet to VB and keep its semantics consistent. | import System.IO
import MorseCode
import MorsePlaySox
main = do
hSetBuffering stdin NoBuffering
text <- getContents
play $ toMorse text
| 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
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.