Camel Case 4

Sort by

recency

|

525 Discussions

|

  • + 0 comments

    C# Solution

    using System; using System.Collections.Generic; using System.IO; using System.Text.RegularExpressions; class Solution { static void Main(String[] args) { /* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution */

        string line;
        while((line = Console.ReadLine()) !=null && line!=""){
            ProcessLine(line);
        }
    
    
    }
    static void ProcessLine(string input){
         if(!string.IsNullOrEmpty(input)){
    
    
            string[] splittedInput = input.Split(';');
            string operation= splittedInput[0];
            string typeOfOperand = splittedInput[1];
            string actualInput = splittedInput[2];
    
            switch(operation){
                case "S":
                    var stringArr = SplitByCapitalLetter(actualInput);
                    string splittedString = string.Join(' ',stringArr);
                    if(typeOfOperand == "M") splittedString = splittedString.Remove(splittedString.IndexOf('('));
                    Console.WriteLine(splittedString);
                    break;
                case "C":
                    switch(typeOfOperand){
                        case "M":
                            var methodOutput = MethodAndVariableFormatting(actualInput);
                            Console.WriteLine($"{methodOutput}()");        
                        break;
                        case "V":
                             var varOutput = MethodAndVariableFormatting(actualInput);
                            Console.WriteLine(varOutput);
                        break;
                        case "C":
                            var classOutput = actualInput.Split(" ")
                                            .Select(s=>CapitalizeFirstLetter(s));
                            Console.WriteLine(string.Join("",classOutput));    
                        break;
                    }
                    break;
    
            }
            }
    }
    

    static string MethodAndVariableFormatting(string input) { var splitted = input.Split(" "); var caplitalizedWords = splitted.Skip(1).Select(s => CapitalizeFirstLetter(s)).ToArray(); var combined = splitted.Take(1).ToArray().Concat(caplitalizedWords); return string.Join("", combined);

    }
    static string CapitalizeFirstLetter(string inputString){
        return $"{inputString[0].ToString().ToUpper()}{inputString.Substring(1)}";
    }
    static string LowerFirstLetter(string inputString){
        return $"{inputString[0].ToString().ToLower()}{inputString.Substring(1)}";
    }
    static string[] SplitByCapitalLetter(string inputString){
        string pattern = @"(?=[A-Z])";
        return Regex.Split(inputString,pattern)
            .Where(s=>!string.IsNullOrEmpty(s))
            .Select(s=>LowerFirstLetter(s))
            .ToArray();
    }
    

    }

  • + 0 comments

    Test cases didn't pass but when checked I typed the same test cases in the custom test case option it worked.

    JS solution

    function processData(input) {
        //Enter your code here
        let lines = input.split('\n');
        for(let line of lines){
            if(line.trim()==='') continue;
            let [operation,type,words]=line.split(';');
            
            if(operation==='S'){
                if(type==='M'){
                     words = words.replace(/\(\)$/,'');}
                    const result = words.split(/(?=[A-Z])/)
                    .map(word => word.toLowerCase()).join(' ');
                    console.log(result); 
                  
                
            }else if(operation==='C'){
                const wordList = words.split(' ');
                if(type==='M'){
                    const result = wordList[0].toLowerCase() +
                     wordList.slice(1).map(word => word.charAt(0).toUpperCase()
                      + word.slice(1)).join('')+'()'
                    console.log(result);
                }else if(type==='C'){
                     const result = wordList
                     .map(word => word.charAt(0).toUpperCase()
                      + word.slice(1)).join('')
                    console.log(result);
                }else if(type==='V'){
                 const result = wordList[0].toLowerCase()+
                  wordList.slice(1).map(word => word.charAt(0).toUpperCase()
                   + word.slice(1)).join('')
                    console.log(result);
                }
            }
        }
    } 
    
  • + 0 comments

    Typescript solution: Please do start from main() and move your way into the inner helper functions to see how the problem was broken down

    Hope this helps!

    function readLine(): string {
        return inputLines[currentLine++];
    }
    
    function prepareTokens(input: string): string[] {
        return input
        .trim()
        .replace(/[{()}]/g, '')
        .split(/(?=[A-Z])|\s+/)
    }
    
    function prepareClassTokens(input: string[]): string[] {
        return input.map(str => str.charAt(0).toUpperCase() + str.slice(1))
    }
    
    function prepareCamelCaseTokens(input: string[]): string[] {
        return input.map((str, n) => {
            if(n === 0) {
                return str.toLowerCase()
            }
            return str.charAt(0).toUpperCase() + str.slice(1)
        })
    }
    
    function processSplit(input: string[]) {
        const toPrint = input.map(token => token.toLowerCase())
        console.log(toPrint.join(' '))
    }
    
    function processCombine(input: string[], type: string) {
            let toPrint: string[]
            if(type === 'C') {
                toPrint = prepareClassTokens(input)
            }
            
            if(type === 'M' || type === 'V') {
                toPrint = prepareCamelCaseTokens(input)   
            }
            
            if(type !== 'M') {
                console.log(toPrint.join(''))
            }
            
            if(type === 'M') {
                console.log(`${toPrint.join('')}()`)
            }
    }
    
    function main() {
        while(currentLine <= inputLines.length-1) {
            const currentString = readLine()
            const [ operation, type, input ] = currentString.split(';')
            
            // Prepare tokens by: 
            // 1) sanitizing the input and
            // 2) normalizing them all into lowercase 
            let tokens: string[]
            tokens = prepareTokens(input)
            
            // Handle split
            if(operation === 'S') {
                processSplit(tokens)
            }
            
            // Handle combine: methods, classes, and variables combine differently
            if(operation === 'C') {
                processCombine(tokens, type)
            }
        }
    }
    
  • + 0 comments

    Kotlin Solution:

    import java.io.*
    import java.util.*
    /**
    
    **/ 
    
    fun split(list: Array<String>) : String{
        val stringList = arrayListOf<String>()
        var currentString = ""
        list[1].toCharArray().forEach {
            if (it.isUpperCase()) {
                if(currentString.isNotBlank()) {
                    stringList.add(currentString)
                }
                currentString = ""
                currentString += it.lowercaseChar()
            } else {
                currentString += it
            }
        }
        stringList.add(currentString.removeSuffix("()"))
        return stringList.joinToString(" ")
    }
    
    fun combine(list: Array<String>) : String {
        val textToJoin = list[1].split(' ').toMutableList()
    
        when(list[0]){
            "M" -> {
                textToJoin.add("()")
            }
            "C" -> {
                textToJoin[0] = textToJoin[0].replaceFirstChar {
                    it.uppercase()
                }
            }
        }
        for(index in 1 until textToJoin.size) {
            textToJoin[index] = textToJoin[index].replaceFirstChar {
                it.uppercase()
            }
        }
        return textToJoin.joinToString("")
    }
    
    fun main(args: Array<String>) {
        val br = BufferedReader(InputStreamReader(System.`in`))
    
        while(br.ready()) {
            val list = br.readLine().split(';')
            val newString = when {
                list.first() == "S" -> {
                    split(list.slice(1..2).toTypedArray())
                }
    
                list.first() == "C" -> {
                    combine(list.slice(1..2).toTypedArray())
                }
    
                else -> ""
            }
            println(newString)
        }
    }
    

    Had some trouble with the InputStreamReader, but after that everything went smoothly

  • + 0 comments
    import java.io.*;
    
    public class CamelCase4 {
    
        private static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        private static BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
    
        public static void main(String[] args) throws IOException {
            while (br.ready()) {
                var line = br.readLine().split(";");
                bw.write(processByType(line));
                bw.newLine();
            }
            bw.flush();
            bw.close();
            br.close();
        }
    
        private static String processByType(String[] line) {
            var operation = line[0];
            var type = line[1];
            switch (type) {
                case "M":
                    return "S".equals(operation) ? splitMethod(line[2]): combinationMethod(line[2]);
                case "C":
                    return "S".equals(operation) ? splitClass(line[2]): combinationClass(line[2]);
                case "V":
                    return "S".equals(operation) ? splitVariable(line[2]): combinationVariable(line[2]);
                default:
                    return "";
            }
        }
    
        private static String combinationMethod(String s) {
            var result = combinationProcess(s.toCharArray());
            return result.append("()").toString();
        }
    
        private static String combinationVariable(String s) {
            var result = combinationProcess(s.toCharArray());
            return result.toString();
        }
    
        private static String combinationClass(String s) {
            var chars = s.toCharArray();
            chars[0] = Character.toUpperCase(chars[0]);
            var result = combinationProcess(chars);
            return result.toString();
        }
    
        private static StringBuilder combinationProcess(char[] s) {
            var result = new StringBuilder();
            for (int i = 0; i < s.length; i++) {
                if (Character.isSpaceChar(s[i])) {
                    result.append(Character.toUpperCase(s[++i]));
                } else {
                    result.append(s[i]);
                }
            }
            return result;
        }
    
        private static String splitMethod(String s) {
            var result = splitProcess(s.substring(0, s.length() - 2).toCharArray());
            return result.toString();
        }
    
        private static String splitClass(String s) {
            var result = splitProcess(s.toCharArray());
            return result.substring(1, result.length());
        }
    
        private static String splitVariable(String s) {
            return splitProcess(s.toCharArray());
        }
    
        private static String splitProcess(char[] s) {
            var result = new StringBuilder();
            for (char c : s) {
                if (Character.isUpperCase(c)) {
                    result.append(" ").append(Character.toLowerCase(c));
                } else {
                    result.append(c);
                }
            }
            return result.toString();
        }
    
    }