Showing posts with label HackerRank. Show all posts
Showing posts with label HackerRank. Show all posts

Monday, April 3, 2023

DNA Health Analysis | HackerRank

int formingMagicSquare(vector<vector<int>> s) {
    // Possible magic squares to compare against
    vector<vector<vector<int>>> magic_squares = {
        {{8, 1, 6}, {3, 5, 7}, {4, 9, 2}},
        {{6, 1, 8}, {7, 5, 3}, {2, 9, 4}},
        {{4, 9, 2}, {3, 5, 7}, {8, 1, 6}},
        {{2, 9, 4}, {7, 5, 3}, {6, 1, 8}},
        {{8, 3, 4}, {1, 5, 9}, {6, 7, 2}},
        {{4, 3, 8}, {9, 5, 1}, {2, 7, 6}},
        {{6, 7, 2}, {1, 5, 9}, {8, 3, 4}},
        {{2, 7, 6}, {9, 5, 1}, {4, 3, 8}}
    };

    int min_cost = INT_MAX;

    // For each possible magic square
    for (auto &magic_square : magic_squares) {
        int cost = 0;

        // For each element in the input matrix and the corresponding element in the magic square
        for (int i = 0; i < 3; i++) {
            for (int j = 0; j < 3; j++) {
                cost += abs(s[i][j] - magic_square[i][j]);
            }
        }

        // Update minimum cost
        min_cost = min(min_cost, cost);
    }

    return min_cost;
}

Matrix Layer Rotation | HackerRank | c++

 void matrixRotation(vector<vector<int>> matrix, int r) {

    int m = matrix.size(), n = matrix[0].size();
    int numLayers = min(m, n) / 2;
   
    // Rotate each layer r times
    for (int layer = 0; layer < numLayers; layer++) {
        int layerHeight = m - 2 * layer, layerWidth = n - 2 * layer;
        int numRotations = r % (2 * (layerHeight + layerWidth - 2));
        while (numRotations--) {
            // Rotate right edge
            for (int i = layer; i < layer + layerHeight - 1; i++) {
                swap(matrix[i][n - layer - 1], matrix[i + 1][n - layer - 1]);
            }
            // Rotate bottom edge
            for (int i = n - layer - 1; i > layer; i--) {
                swap(matrix[m - layer - 1][i], matrix[m - layer - 1][i - 1]);
            }
            // Rotate left edge
            for (int i = m - layer - 1; i > layer; i--) {
                swap(matrix[i][layer], matrix[i - 1][layer]);
            }
            // Rotate top edge
            for (int i = layer; i < layer + layerWidth - 2; i++) {
                swap(matrix[layer][i], matrix[layer][i + 1]);
            }
        }
    }
   
    // Print the rotated matrix
    for (int i = 0; i < m; i++) {
        for (int j = 0; j < n; j++) {
            cout << matrix[i][j] << " ";
        }
        cout << endl;
    }
}

Sunday, July 17, 2022

Duplicated Products | C# | HackerRank

ISet<string> uniqueProducts = new HashSet<string>();
for(int i = 0; i < name.Count; i++)
{
    uniqueProducts.Add(name[i] + " " + price[i] + " " + weight[i]);
}
return name.Count = uniqueProducts.Count; 

Frequency of Max Value | C# | HackerRank

public static List<int> FrequencyOfMaxValue(List<int> numbers,
    List<int> q)
{
    List<int> result = new List<int>();
    int n = numbers.Count;
    int[,] table = new int[2,n];
    Dictionary<int, int> counts = new Dictionary<int, int>();
    table[0,n-1] = numbers[n-1];
    table[1,n-1] = 1;
    counts.Add(numbers[n-1], 1);
    for(int i = n-2; i >= 0; i--)
    {
        if(!counts.ContainsKey(numbers[i]))
            counts.Add(numbers[i],1);
        else
            counts[numbers[i]]++;

        if(numbers[i] > table[0, i+1])
        {
            table[0,i] = numbers[i];
            table[1,i] = 1;
        }
        else
        {
            table[0,i] = table[0, i+1];
            table[1,i] = counts[table[0,i]];
        }
    }
    for(int i = 0; i < n; i++)
    {
        result.Add(table[1,q[i] - 1]);
    }
    return result;
} 

Equal Levels | HackerRank

public static int updateTimes(List<int> signalOne,
     List<int> signalTwo)
{
    int noOfUpdate = 0;
    int maxEqual = int.MinValue;
    int length;
    int signalOneCount = signalOne.Count;
    int signalTwoCount = signalTwo.Count;

    if(signalOneCount < signalTwoCount)
        length = signalOneCount;
    else
        length = signalTwoCount;

    for(int i = 0; i < length; i++)
    {
        if(signalOne[i] == signalTwo[i])
        {
            if(maxEqual < signalOne[i])
            {
                maxEqual = signalOne[i];
                noOfUpdate++;
            }
        }
    }
    return noOfUpdate;
} 

Sunday, June 5, 2022

Customer List | HackerRank Certification | React


 import React, {useState} from "react";
import "./index.css";

function CustomerList(){
    const[customer, setCustomer] = useState("");
    const[customers, setCustomers] = useState([]);

    const handleSubmit = e => {
        e.preventDefault();
        if(customers.length === 0)
            return;
        setCustomers([...customers,
            {name:customer, count:customer.length}]);
        setCustomer("");
    }

    let rendered = "";

    if(customer.length !== 0){
        rendered = <ul className="styled mt-50"
                        data-testid="customer-list">
                        {customers && customers.map(cus => {
                         return(
                           <li className="slide-up-fade-in"
                            data-testid={"list-item"+cus.count}
                            key={"list-item"+cus.count}>
                            {cus.name}
                           </li>
                         )
                        })}
                    </ul>
    }

    return(
        <div className="mt-75 layout-column
            justify-content-center
            align-items-center">
            <section className="layout-row
                align-items-center
                justify-content-center">
                <input type="text"
                    className="large"
                    placeholder="Name" data-testid="app-input"
                    value={customer}
                    onChange={e => setCustomer(e.target.value)} />
                <button type="submit"
                    className="ml-30"
                    data-testid="submit-button"
                    onClick={handleSubmit}>
                    Add Customer
                </button>
            </section>
            {rendered}
        </div>
    );
}


export default CustomerList

Monday, May 30, 2022

Count String Permutations | HackerRank Certification

Count all possible N-length vowel permutations that can be generated based on the given conditions

Given an integer N, the task is to count the number of N-length strings consisting of lowercase vowels that can be generated based the following conditions:

  • Each ‘a’ may only be followed by an ‘e’.
  • Each ‘e’ may only be followed by an ‘a’ or an ‘i’.
  • Each ‘i’ may not be followed by another ‘i’.
  • Each ‘o’ may only be followed by an ‘i’ or a ‘u’.
  • Each ‘u’ may only be followed by an ‘a’.a

nput: N = 1
Output: 5
Explanation: All strings that can be formed are: “a”, “e”, “i”, “o” and “u”.

Input: N = 2
Output: 10
Explanation: All strings that can be formed are: “ae”, “ea”, “ei”, “ia”, “ie”, “io”, “iu”, “oi”, “ou” and “ua”.


using System;
using System.Collections.Generic;
class StringPermutation {
   
    static int countVowelPermutation(int n)
    {
   
        int MOD = (int)(1e9 + 7);

        long[,] dp = new long[n + 1, 5];

        for (int i = 0; i < 5; i++) {
            dp[1, i] = 1;
        }

        List<List<int>> relation = new List<List<int>>();
        relation.Add(new List<int> { 1 });
        relation.Add(new List<int> { 0, 2 });
        relation.Add(new List<int> { 0, 1, 3, 4 });
        relation.Add(new List<int> { 2, 4 });
        relation.Add(new List<int> { 0 });

        for (int i = 1; i < n; i++)
        {

            for (int u = 0; u < 5; u++)
            {
                dp[i + 1, u] = 0;

                foreach(int v in relation[u])
                {

                    dp[i + 1, u] += dp[i, v] % MOD;
                }
            }
        }

        long ans = 0;

        for (int i = 0; i < 5; i++)
        {
            ans = (ans + dp[n, i]) % MOD;
        }

        return (int)ans;
    }

    static void Main() {
        int N = 2;
        Console.WriteLine(countVowelPermutation(N));
    }
}

Condensed List | HackerRank Certification | Remove repeated node from a Singly Linked List

 Given a list of integers, remove any nodes that have values that have previously occurred in the list and return a reference to the head of the list.   

For e.g: 

Linked List

Input : 3 --> 4 --> 3 --> 6

Output: 3 --> 4 --> 6 


public static SinglyLinkedListNode(SinglyLinkedListNode head)
{
    var hSet = new HashSet<int>();
    SinglyLinkedListNode newList = new SinglyLinkedListNode();
    while(head != null)
    {
        hSet.Add(head.data);
        head = head.next;
    }

    foreach(int i in hSet)
    {
        newList.InsertNode(i);
    }
    return (newList.head);

}

Sunday, April 17, 2022

Staircase | HackerRank | C#

 This is a staircase of size :

             #
          ##
      ###
  ####

Its base and height are both equal to . It is drawn using # symbols and spaces. The last line is not preceded by any spaces.

Write a program that prints a staircase of size .

Function Description

Complete the staircase function in the editor below.

staircase has the following parameter(s):

  • int n: an integer

Print

Print a staircase as described above.

Input Format

A single integer, , denoting the size of the staircase.

Constraints

 .

Output Format

Print a staircase of size  using # symbols and spaces.

Note: The last line must have  spaces in it.

Sample Input

6 

Sample Output

                    #
                 ##
             ###
         ####
     #####
######

Explanation

The staircase is right-aligned, composed of # symbols and spaces, and has a height and width of .


Solution

    public static void staircase(int n)
    {
        for(int i=0; i < n; i++)
        {
            Console.WriteLine(new String('#', i+1).PadLeft(n));
        }      
    }

Plus Minus | HackerRank | C#

 Given an array of integers, calculate the ratios of its elements that are positive, negative, and zero. Print the decimal value of each fraction on a new line with  places after the decimal.

Note: This challenge introduces precision problems. The test cases are scaled to six decimal places, though answers with absolute error of up to  are acceptable.

Example

There are  elements, two positive, two negative and one zero. Their ratios are  and . Results are printed as:

0.400000
0.400000
0.200000

Function Description

Complete the plusMinus function in the editor below.

plusMinus has the following parameter(s):

  • int arr[n]: an array of integers

Print
Print the ratios of positive, negative and zero values in the array. Each value should be printed on a separate line with  digits after the decimal. The function should not return a value.

Input Format

The first line contains an integer, , the size of the array.
The second line contains  space-separated integers that describe .

Constraints


Output Format

Print the following  lines, each to  decimals:

  1. proportion of positive values
  2. proportion of negative values
  3. proportion of zeros

Sample Input

STDIN           Function
-----           --------
6               arr[] size n = 6
-4 3 -9 0 4 1   arr = [-4, 3, -9, 0, 4, 1]

Sample Output

0.500000
0.333333
0.166667

Explanation

There are  positive numbers,  negative numbers, and  zero in the array.
The proportions of occurrence are positive: , negative:  and zeros: .


SOLUTION

    public static void plusMinus(List<int> arr)
    {
        decimal pos = 0, neg = 0, zer = 0;
        int len = arr.Count;
        for(int i = 0; i < len; i++)
        {
            if(arr[i] > 0)pos++;
            else if(arr[i] < 0)neg++;
            else zer++;
        }
        Console.WriteLine("{0:N6}", pos/len);
        Console.WriteLine("{0:N6}", neg/len);
        Console.WriteLine("{0:N6}", zer/len);
    }

horizontal ads