Sort by

recency

|

18 Discussions

|

  • + 0 comments
    #include <assert.h>
    #include <ctype.h>
    #include <limits.h>
    #include <math.h>
    #include <stdbool.h>
    #include <stddef.h>
    #include <stdint.h>
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    
    char* readline();
    char* ltrim(char*);
    char* rtrim(char*);
    
    int parse_int(char*);
    
    /*
     * Complete the 'solve' function below.
     *
     * The function is expected to return a DOUBLE.
     * The function accepts STRING s as parameter.
     */
    bool is_palindrome(const char* s){
        int n=strlen(s);
        for(int i=0;i<n/2;++i) {
            if(s[i]!=s[n-i-1]) {
                return false;
            }
        }
        return true;
    }
    
    
    
    int min_swaps_to_palindrome(char* s){
        int n=strlen(s);
        int swaps=0;
        
        for(int i=0;i<n/2;++i) {
            int left = i;
            int right = n-left-1;
            
            while(left<right && s[left] != s[right]){
                right--;
                }
            if (left==right) {
                if(n % 2== 1) {
            for (int j=right;j<n-left-1;++j) {
                char temp = s[j];
                s[j]=s[j+1];
                s[j+1]=temp;
                swaps++;
            } continue;
                } else {
                        return -1;
                    }
                } else {
                        for (int j=right;j<n-left-1;++j) {
                            char temp =s[j];
                            s[j]=s[j+1];
                            s[j+1]=temp;
                            swaps++;
                        }
                    }
        } 
        return swaps;
    
    }
    
    
    
    
    double solve(char* s) {
        if(is_palindrome(s)) {
            return 0.0;
        }
        int min_swaps=min_swaps_to_palindrome(s);
        if(min_swaps == -1) {
            return (double)INT_MAX;
        }
        return(double)min_swaps;
        }
        
    int main()
    {
        FILE* fptr = fopen(getenv("OUTPUT_PATH"), "w");
    
        int t = parse_int(ltrim(rtrim(readline())));
    
        for (int t_itr = 0; t_itr < t; t_itr++) {
            char* s = readline();
    
            double result = solve(s);
    
            fprintf(fptr, "%lf\n", result);
        }
    
        fclose(fptr);
    
        return 0;
    }
    
    char* readline() {
        size_t alloc_length = 1024;
        size_t data_length = 0;
    
        char* data = malloc(alloc_length);
    
        while (true) {
            char* cursor = data + data_length;
            char* line = fgets(cursor, alloc_length - data_length, stdin);
    
            if (!line) {
                break;
            }
    
            data_length += strlen(cursor);
    
            if (data_length < alloc_length - 1 || data[data_length - 1] == '\n') {
                break;
            }
    
            alloc_length <<= 1;
    
            data = realloc(data, alloc_length);
    
            if (!data) {
                data = '\0';
    
                break;
            }
        }
    
        if (data[data_length - 1] == '\n') {
            data[data_length - 1] = '\0';
    
            data = realloc(data, data_length);
    
            if (!data) {
                data = '\0';
            }
        } else {
            data = realloc(data, data_length + 1);
    
            if (!data) {
                data = '\0';
            } else {
                data[data_length] = '\0';
            }
        }
    
        return data;
    }
    
    char* ltrim(char* str) {
        if (!str) {
            return '\0';
        }
    
        if (!*str) {
            return str;
        }
    
        while (*str != '\0' && isspace(*str)) {
            str++;
        }
    
        return str;
    }
    
    char* rtrim(char* str) {
        if (!str) {
            return '\0';
        }
    
        if (!*str) {
            return str;
        }
    
        char* end = str + strlen(str) - 1;
    
        while (end >= str && isspace(*end)) {
            end--;
        }
    
        *(end + 1) = '\0';
    
        return str;
    }
    
    int parse_int(char* str) {
        char* endptr;
        int value = strtol(str, &endptr, 10);
    
        if (endptr == str || *endptr != '\0') {
            exit(EXIT_FAILURE);
        }
    
        return value;
    }
    

    Where is the issue???

    w

  • + 0 comments

    include

    include

    include

    include

    include

    include

    include

    include

    include

    include

    char* readline(); char* ltrim(char*); char* rtrim(char*);

    int parse_int(char*);

    /* * Complete the 'solve' function below. * * The function is expected to return a DOUBLE. * The function accepts STRING s as parameter. / bool is_palindrome(const char s){ int n=strlen(s); for(int i=0;i

    int min_swaps_to_palindrome(char* s){ int n=strlen(s); int swaps=0;

    for(int i=0;i<n/2;++i) {
        int left = i;
        int right = n-left-1;
    
        while(left<right && s[left] != s[right]){
            right--;
            }
        if (left==right) {
            if(n % 2== 1) {
        for (int j=right;j<n-left-1;++j) {
            char temp = s[j];
            s[j]=s[j+1];
            s[j+1]=temp;
            swaps++;
        } continue;
            } else {
                    return -1;
                }
            } else {
                    for (int j=right;j<n-left-1;++j) {
                        char temp =s[j];
                        s[j]=s[j+1];
                        s[j+1]=temp;
                        swaps++;
                    }
                }
    } 
    return swaps;
    

    }

    double solve(char* s) { if(is_palindrome(s)) { return 0.0; } int min_swaps=min_swaps_to_palindrome(s); if(min_swaps == -1) { return (double)INT_MAX; } return(double)min_swaps; }

    int main() { FILE* fptr = fopen(getenv("OUTPUT_PATH"), "w");

    int t = parse_int(ltrim(rtrim(readline())));
    
    for (int t_itr = 0; t_itr < t; t_itr++) {
        char* s = readline();
    
        double result = solve(s);
    
        fprintf(fptr, "%lf\n", result);
    }
    
    fclose(fptr);
    
    return 0;
    

    }

    char* readline() { size_t alloc_length = 1024; size_t data_length = 0;

    char* data = malloc(alloc_length);
    
    while (true) {
        char* cursor = data + data_length;
        char* line = fgets(cursor, alloc_length - data_length, stdin);
    
        if (!line) {
            break;
        }
    
        data_length += strlen(cursor);
    
        if (data_length < alloc_length - 1 || data[data_length - 1] == '\n') {
            break;
        }
    
        alloc_length <<= 1;
    
        data = realloc(data, alloc_length);
    
        if (!data) {
            data = '\0';
    
            break;
        }
    }
    
    if (data[data_length - 1] == '\n') {
        data[data_length - 1] = '\0';
    
        data = realloc(data, data_length);
    
        if (!data) {
            data = '\0';
        }
    } else {
        data = realloc(data, data_length + 1);
    
        if (!data) {
            data = '\0';
        } else {
            data[data_length] = '\0';
        }
    }
    
    return data;
    

    }

    char* ltrim(char* str) { if (!str) { return '\0'; }

    if (!*str) {
        return str;
    }
    
    while (*str != '\0' && isspace(*str)) {
        str++;
    }
    
    return str;
    

    }

    char* rtrim(char* str) { if (!str) { return '\0'; }

    if (!*str) {
        return str;
    }
    
    char* end = str + strlen(str) - 1;
    
    while (end >= str && isspace(*end)) {
        end--;
    }
    
    *(end + 1) = '\0';
    
    return str;
    

    }

    int parse_int(char* str) { char* endptr; int value = strtol(str, &endptr, 10);

    if (endptr == str || *endptr != '\0') {
        exit(EXIT_FAILURE);
    }
    
    return value;
    

    } where is the issue

  • + 0 comments

    Given a string, you keep swapping any two characters in the string randomly till the string becomes a palindrome. What is the expected number of swaps you will make? There will always be at least one palindrome which can be formed with the letters of the given string.

    Input: The first line contains the number of test cases T. Each of the next T lines contains a string each.

    Output: Output T lines containing the answer for the corresponding test case. Print the answer correct to 4 decimal places.

    Constraints: T <= 10000 The length of the string will be at most 8 characters. The string will consist of only lower-case letters 'a'-'z'.

    Sample Input:

    4
    b
    bb
    abb
    cbaabbb Sample Output:

    0.0000
    0.0000
    3.0000
    59.3380 Explanation:

    For the first two cases, the string is already a palindrome so no swaps are needed.

    For the third case, there are 3 possible swaps. The string will become "bab","bba" or remain "abb" with 1/3rd probability each. It's easy to see that the expected number of swaps needed is 3.0000************

    For the last case, the answer is 59.337962..., which should be printed as 59.3380

  • + 1 comment
    #!/bin/python3
    import os
    import sys
    from collections import Counter
    
    def mapString(s):
        counter = 0
        map_val = {}
        s_ = ''
        for el in s:
            if el not in map_val:
                map_val[el] = counter
                counter += 1
            s_ += str(map_val[el])
        return s_
    def isValid(s):
        if s == s[::-1]:
            return False
        char_counts = Counter(s)
        no_odds = 0
        for (el, c)in char_counts.items():
            if c % 2:
                no_odds += 1
        if len(s) % 2:
            return not bool(no_odds - 1)
        return not bool(no_odds)
    
    
    def generateAllPossible(s, allStates):
        s = mapString(s)
        if s in allStates:
            return
        allStates.append(s)
        if len(s) < 8:
            generateAllPossible(s + '0', allStates)
            generateAllPossible(s + '1', allStates)
            generateAllPossible(s + '2', allStates)
            generateAllPossible(s + '3', allStates)
    def generateTransitionMatrix(tr_matrix, states, state_to_index):
        for s in states:
            x_val = state_to_index[s]
            no_of_swap = len(s) * (len(s) - 1) / 2
            for i in range(len(s)):
                for j in range(i + 1, len(s)):
                    s_ = mapString(s[:i] + s[j] + s[i+1:j] + s[i] + s[j+1:len(s)])
                    if isValid(s_):
                        y_val = state_to_index[s_]
                        tr_matrix[x_val][y_val] -= 1/no_of_swap
    def swap_row(m, i, j):
        temp_row = m[i]
        m[i] = m[j]
        m[j] = temp_row
    def forwardElim(m):
    
        for k in range(len(m)):
            i_max = k
            v_max = m[i_max][k]
            for  i in range(k+1, len(m)):
                if (abs(m[i][k]) > v_max):
                    v_max = m[i][k], i_max = i
            if (i_max != k):
                swap_row(m, k, i_max);
    
            for i in range(k+1, len(m)):
                f = m[i][k] / m[k][k];
                for j in range(k+1,len(m) + 1):
                    m[i][j] -= m[k][j] * f
                m[i][k] = 0
    def backSub(m):
        x = [0 for _ in range(len(m))]
        N = len(m)
        for i in reversed(range(N)):
            x[i] = m[i][N]
            for j in range(i+1, N):
                x[i] -= m[i][j] * x[j]
            x[i] = x[i] / m[i][i]
        return x
    def findSolutions(tr_matrix):
        forwardElim(tr_matrix);
        return backSub(tr_matrix)
    
    def preprocess():
        states = []
        generateAllPossible('', states)
        states = list(filter(isValid, states))
        tr_matrix = [[float(i == j) for i in range(len(states))] for j in range(len(states))]
        states_to_index = {}
        for (ind, s) in enumerate(states):
            states_to_index[s] = ind
        generateTransitionMatrix(tr_matrix,states, states_to_index)
        for i in tr_matrix:
            i += [1]
        ans = findSolutions(tr_matrix)
        return (ans, states_to_index)
    if __name__ == '__main__':
        fptr = open(os.environ['OUTPUT_PATH'], 'w')
        (ans, states_to_index) = preprocess()
        t = int(input())
    
        for t_itr in range(t):
            s = input()
            if(len(s) != 1 and s != s[::-1]):
                index = states_to_index[mapString(s)]
                result = round(ans[index],4)
            else:
                result = 0
            fptr.write('%.4f\n'%result)
    
        fptr.close()
    

    getting a timeout, how do i speed it up

  • + 0 comments

    can anyone keep answer in c