DEV Community

dev.to staff
dev.to staff

Posted on

Daily Challenge #212 - DNA to RNA

Deoxyribonucleic acid, DNA is the primary information storage molecule in biological systems. It is composed of four nucleic acid bases Guanine ('G'), Cytosine ('C'), Adenine ('A'), and Thymine ('T').

Ribonucleic acid, RNA, is the primary messenger molecule in cells. RNA differs slightly from DNA its chemical structure and contains no Thymine. In RNA Thymine is replaced by another nucleic acid Uracil ('U').

Create a function which translates a given DNA string into RNA.

For example:
DNAtoRNA("GCAT") returns ("GCAU")
The input string can be of arbitrary length - in particular, it may be empty. All input is guaranteed to be valid, i.e. each input string will only ever consist of 'G', 'C', 'A' and/or 'T'.

Tests

DNAtoRNA("TTTT")
DNAtoRNA("GCAT")
DNAtoRNA("GACCGCCGCC")

Good luck!


This challenge comes from torret on CodeWars. Thank you to CodeWars, who has licensed redistribution of this challenge under the 2-Clause BSD License!

Want to propose a challenge idea for a future post? Email yo+challenge@dev.to with your suggestions!

Top comments (12)

Collapse
 
not_jffrydsr profile image
@nobody

Super simple! I love the polyglot answers 👌🏿
Clojure

(ns dailyChallenge.206)

(def- NUCLEOTIDES
  "Valid Nucleotides"
  (re-pattern "G|C|T|A|U"))

(defn DNA->RNA [sequence] 
  "validates and converts DNA pairs to RNA"
 {:pre [(!= "" (re-match NUCLEOTIDES (uppercase sequence))]}
  ;;Java.String method interop
  (.toUpperCase (replace sequence #"t|T" "u")))
Collapse
 
bravemaster619 profile image
bravemaster619

Ruby

def DNAtoRNA(dna)
  reg_dna = /^(G|C|A|T)*$/i
  if dna.match(reg_dna)
    dna.gsub(/(T|t)/, 'U').upcase
  else
    raise "Not a valid DNA string"
  end
end

JavaScript

const DNAtoRNA = (dna) => {
   const dnaRegex = /^(G|C|A|T)*$/gi
   if (dnaRegex.test(dna)) {
      return dna.replace(/t/gi, 'U').toUpperCase()
   } else {
      throw new Error("Not a valid DNA string")
   }
}

PHP

function DNAtoRNA($dna) {
    $dnaRegex = "/^(G|C|A|T)*$/i";
    if (preg_match($dnaRegex, $dna)) {
        return strtoupper(str_ireplace("T", "U", $dna));
    } else {
        throw new \Exception("Not a valid DNA string");
    };
}
Collapse
 
mvdsman profile image
Mark vd Sman

I wanted to see what this challenge was about, because I like these combinations of combined fields. So nice to see this come by!
But I am uncomfortable with the fact that this is not the correct way to code transcription (DNA to RNA). RNA is complementary to DNA because it is double-stranded: therefore GCAT should result in CGUA (on a side note: direction is also very important).

I'm curious if there is any particular reason why it is done in the way you described it?

Collapse
 
qm3ster profile image
Mihail Malo • Edited

Roost

fn dtoa(dna: &str) -> String {
    dna.chars().map(|c| match c {
        'G' | 'C' | 'A' => c,
        'T' => 'U',
        _ => panic!("you did this to yourself"),
    }).collect()
}
fn main() {
    for x in &["TTTT", "GCAT", "GACCGCCGCC", "💩"] {
        println!("{}=>{}", x, dtoa(x));
    }
}

"Rust"

use itertools::Itertools; // 0.9.0

#[derive(Debug)]
enum DToAError {
    Scat(usize, char),
}
use DToAError::*;

impl std::fmt::Display for DToAError {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        match self {
            Scat(i, c) => write!(f, "Is this a joke? At index {}, what is `{}`?! No you can't \"have the processed values back\", get out!", i, c),
        }
    }
}

impl std::error::Error for DToAError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        None
    }
}

fn dtoa(dna: &str) -> Result<String, DToAError> {
    dna.chars()
        .enumerate()
        .map(|(i, c)| {
            Ok(match c {
                'G' | 'C' | 'A' => c,
                'T' => 'U',
                _ => return Err(Scat(i, c)),
            })
        })
        .fold_results(String::with_capacity(dna.len()), |mut s, c| {
            s.push(c);
            s
        })
}
fn main() {
    for x in &["TTTT", "GCAT", "GACCGCCGCC", "💩"] {
        match dtoa(x) {
            Ok(res) => println!("{}=>{}", x, res),
            Err(err) => println!("{}=>OOPS: {}", x, err),
        }
    }
}

It works lol

When you don't listen at all

fn main() {
    for x in &["TTTT", "GCAT", "GACCGCCGCC", "💩"] {
        println!("{}=>{}", x, x.replace('T', "U"))
    }
}
Collapse
 
jburnham96 profile image
James • Edited

Javascript solution:

function DNAtoRNA(dna) {
  return dna.replace(/T/g, 'U');
}
Collapse
 
rburmorrison profile image
Ryan Burmeister-Morrison • Edited

Ruby

def DNAToRNA(str); str.gsub(/T/i, 'U') end
Collapse
 
nilbert profile image
Nilbert

Ruby

DNAtoRNA = ->(str) { str.gsub!(/T/,'U')}
DNAtoRNA.call('TTTT')
=> "UUUU"
DNAtoRNA.call('GCAT')
=> "GCAU"
Collapse
 
aminnairi profile image
Amin

Elm

dnaToRna : String -> String
dnaToRna = String.replace "T" "U"
Collapse
 
kesprit profile image
kesprit

My Swift solution :

func DNAtoRNA(string: String) -> String {
    String(string.map { $0 == "T" ? "U" : $0 })
}
Collapse
 
vidit1999 profile image
Vidit Sarkar

Python solution

DNAtoRNA = lambda dna : dna.replace('T','U')
Collapse
 
vidit1999 profile image
Vidit Sarkar

C++ solution

string DNAtoRNA(string dna){
    replace(dna.begin(),dna.end(),'T','U');
    return dna;
}