Open In App

Minimal operations to make a number magical

Last Updated : 31 Jul, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

Given a 6 digit number, calculate the minimum number of digits that needs to be replaced in order to make the number magical. The number is considered magical if the sum of first three digits equals to the sum of last three digits. In one operation, we can choose a digit at any position and replace it with any arbitrary digit. 

Examples : 

Input: 123456 
Output: 2 
Explanation : Replace 4 with 0 and 5 with 0,
              then number = 123006, where 
              1 + 2 + 3 = 0 + 0 + 6,
              hence number of replacements
              done = 2  

Input: 111000
Output: 1
Explanation: Replace 0 with 3, then 
             number = 111030, where 
             1 + 1 + 1 = 0 + 3 + 0,
             hence number of replacements
             done = 1

Approach: The best approach will be to check with all the magical numbers and the number of replacements needed. Run a loop that generates all 6 digit numbers. Check if that number is magical, if it is then simply calculate the number of replacements needs to be done and compare with the ans, if it is smaller then make it the ans and at the end return ans.

Below is the implementation of the above approach.  

C++




// CPP program to make a number magical
#include "bits/stdc++.h"
using namespace std;
 
// function to calculate the minimal changes
int calculate(string s)
{
    // maximum digits that can be changed
    int ans = 6;
 
    // nested loops to generate all 6
    // digit numbers
    for (int i = 0; i < 10; ++i) {
        for (int j = 0; j < 10; ++j) {
            for (int k = 0; k < 10; ++k) {
                for (int l = 0; l < 10; ++l) {
                    for (int m = 0; m < 10; ++m) {
                        for (int n = 0; n < 10; ++n) {
                            if (i + j + k == l + m + n) {
                                 
                                // counter to count the number
                                // of change required
                                int c = 0;
                                 
                                // if first digit is equal
                                if (i != s[0] - '0')
                                    c++;
                                     
                                // if 2nd digit is equal   
                                if (j != s[1] - '0')
                                    c++;
                                 
                                // if 3rd digit is equal   
                                if (k != s[2] - '0')
                                    c++;
                                 
                                // if 4th digit is equal   
                                if (l != s[3] - '0')
                                    c++;
                                     
                                // if 5th digit is equal   
                                if (m != s[4] - '0')
                                    c++;
                                     
                                // if 6th digit is equal   
                                if (n != s[5] - '0')
                                    c++;
 
                                // checks if less than the
                                // previous calculate changes
                                if (c < ans)
                                    ans = c;
                            }
                        }
                    }
                }
            }
        }
    }
     
    // returns the answer
    return ans;
}
 
// driver program to test the above function
int main()
{
    // number stored in string
    string s = "123456";
 
    // prints the minimum operations
    cout << calculate(s);
}


Java




// java program to make a number magical
import java.io.*;
  
class GFG {
 
// function to calculate the minimal changes
static int calculate(String s)
{
    // maximum digits that can be changed
    int ans = 6;
 
    // nested loops to generate
    // all 6 digit numbers
    for (int i = 0; i < 10; ++i) {
        for (int j = 0; j < 10; ++j) {
            for (int k = 0; k < 10; ++k) {
                for (int l = 0; l < 10; ++l) {
                    for (int m = 0; m < 10; ++m) {
                        for (int n = 0; n < 10; ++n) {
                            if (i + j + k == l + m + n) {
                                 
                                // counter to count the number
                                // of change required
                                int c = 0;
                                 
                                // if first digit is equal
                                if (i != s.charAt(0) - '0')
                                    c++;
                                     
                                // if 2nd digit is equal
                                if (j != s.charAt(1) - '0')
                                    c++;
                                 
                                // if 3rd digit is equal
                                if (k != s.charAt(2) - '0')
                                    c++;
                                 
                                // if 4th digit is equal
                                if (l != s.charAt(3) - '0')
                                    c++;
                                     
                                // if 5th digit is equal
                                if (m != s.charAt(4) - '0')
                                    c++;
                                     
                                // if 6th digit is equal
                                if (n != s.charAt(5) - '0')
                                    c++;
 
                                // checks if less than the
                                // previous calculate changes
                                if (c < ans)
                                    ans = c;
                            }
                        }
                    }
                }
            }
        }
    }
     
    // returns the answer
    return ans;
}
 
   // Driver code
    static public void main (String[] args)
    {
        // number stored in string
        String s = "123456";
 
        // prints the minimum operations
        System.out.println(calculate(s));
    }
}
 
// This code is contributed by vt_m.


Python3




# Python 3 program to make a number magical
  
# function to calculate the minimal changes
def calculate( s):
 
    # maximum digits that can be changed
    ans = 6
  
    # nested loops to generate all 6
    # digit numbers
    for i in range(10):
        for j in range(10):
            for k in range(10):
                for l in range(10):
                    for  m in range(10):
                        for n in range(10):
                            if (i + j + k == l + m + n):
                                  
                                # counter to count the number
                                # of change required
                                c = 0
                                  
                                # if first digit is equal
                                if (i != ord(s[0]) - ord('0')):
                                    c+=1
                                      
                                # if 2nd digit is equal   
                                if (j != ord(s[1]) - ord('0')):
                                    c+=1
                                  
                                # if 3rd digit is equal   
                                if (k != ord(s[2]) - ord('0')):
                                    c+=1
                                  
                                # if 4th digit is equal   
                                if (l != ord(s[3]) - ord('0')):
                                    c+=1
                                      
                                # if 5th digit is equal   
                                if (m != ord(s[4]) - ord('0')):
                                    c+=1
                                      
                                # if 6th digit is equal   
                                if (n != ord(s[5]) - ord('0')):
                                    c+=1
  
                                # checks if less than the
                                # previous calculate changes
                                if (c < ans):
                                    ans = c
      
    # returns the answer
    return ans
  
# driver program to test the above function
if __name__ == "__main__":
     
    # number stored in string
    s = "123456"
  
    # prints the minimum operations
    print(calculate(s))


C#




// C# program to make a number magical
using System;
 
class GFG {
 
// function to calculate the minimal changes
static int calculate(string s)
{
    // maximum digits that can be changed
    int ans = 6;
 
    // nested loops to generate
    // all 6 digit numbers
    for (int i = 0; i < 10; ++i) {
        for (int j = 0; j < 10; ++j) {
            for (int k = 0; k < 10; ++k) {
                for (int l = 0; l < 10; ++l) {
                    for (int m = 0; m < 10; ++m) {
                        for (int n = 0; n < 10; ++n) {
                            if (i + j + k == l + m + n) {
                                 
                                // counter to count the number
                                // of change required
                                int c = 0;
                                 
                                // if first digit is equal
                                if (i != s[0] - '0')
                                    c++;
                                     
                                // if 2nd digit is equal
                                if (j != s[1] - '0')
                                    c++;
                                 
                                // if 3rd digit is equal
                                if (k != s[2] - '0')
                                    c++;
                                 
                                // if 4th digit is equal
                                if (l != s[3] - '0')
                                    c++;
                                     
                                // if 5th digit is equal
                                if (m != s[4] - '0')
                                    c++;
                                     
                                // if 6th digit is equal
                                if (n != s[5] - '0')
                                    c++;
 
                                // checks if less than the
                                // previous calculate changes
                                if (c < ans)
                                    ans = c;
                            }
                        }
                    }
                }
            }
        }
    }
     
    // returns the answer
    return ans;
}
 
    // Driver code
    static public void Main ()
    {
        // number stored in string
        string s = "123456";
 
        // prints the minimum operations
        Console.WriteLine(calculate(s));
         
    }
}
 
// This code is contributed by vt_m.


PHP




<?php
// PHP program to make a number magical
 
// function to calculate
// the minimal changes
function calculate($s)
{
    // maximum digits that
    // can be changed
    $ans = 6;
 
    // nested loops to generate
    //  all 6 digit numbers
    for ($i = 0; $i < 10; ++$i) {
        for ($j = 0; $j < 10; ++$j) {
            for ($k = 0; $k < 10; ++$k) {
                for ( $l = 0; $l < 10; ++$l) {
                    for ($m = 0; $m < 10; ++$m) {
                        for ( $n = 0; $n < 10; ++$n) {
                            if ($i + $j + $k == $l + $m + $n) {
                                 
                                // counter to count the number
                                // of change required
                                $c = 0;
                                 
                                // if first digit is equal
                                if ($i != $s[0] - '0')
                                    $c++;
                                     
                                // if 2nd digit is equal
                                if ($j != $s[1] - '0')
                                    $c++;
                                 
                                // if 3rd digit is equal
                                if ($k != $s[2] - '0')
                                    $c++;
                                 
                                // if 4th digit is equal
                                if ($l != $s[3] - '0')
                                    $c++;
                                     
                                // if 5th digit is equal
                                if ($m != $s[4] - '0')
                                    $c++;
                                     
                                // if 6th digit is equal
                                if ($n != $s[5] - '0')
                                    $c++;
 
                                // checks if less than the
                                // previous calculate changes
                                if ($c < $ans)
                                    $ans = $c;
                            }
                        }
                    }
                }
            }
        }
    }
     
    // returns the answer
    return $ans;
}
 
// Driver Code
// number stored in string
$s = "123456";
 
// prints the minimum operations
echo calculate($s);
 
// This code is contributed by ajit.
?>


Javascript




<script>
 
// Javascript program to make a number magical
 
// Function to calculate the minimal changes
function calculate(s)
{
     
    // Maximum digits that can be changed
    let ans = 6;
 
    // Nested loops to generate
    // all 6 digit numbers
    for(let i = 0; i < 10; ++i)
    {
        for(let j = 0; j < 10; ++j)
        {
            for(let k = 0; k < 10; ++k)
            {
                for(let l = 0; l < 10; ++l)
                {
                    for(let m = 0; m < 10; ++m)
                    {
                        for(let n = 0; n < 10; ++n)
                        {
                            if (i + j + k == l + m + n)
                            {
                                 
                                // Counter to count the number
                                // of change required
                                let c = 0;
 
                                // If first digit is equal
                                if (i != s[0] - '0')
                                    c++;
 
                                // If 2nd digit is equal
                                if (j != s[1] - '0')
                                    c++;
 
                                // If 3rd digit is equal
                                if (k != s[2] - '0')
                                    c++;
 
                                // If 4th digit is equal
                                if (l != s[3] - '0')
                                    c++;
 
                                // If 5th digit is equal
                                if (m != s[4] - '0')
                                    c++;
 
                                // If 6th digit is equal
                                if (n != s[5] - '0')
                                    c++;
 
                                // Checks if less than the
                                // previous calculate changes
                                if (c < ans)
                                    ans = c;
                            }
                        }
                    }
                }
            }
        }
    }
 
    // Returns the answer
    return ans;
}
 
// Driver code
 
// Number stored in string
let s = "123456";
 
// Prints the minimum operations
document.write(calculate(s));
 
// This code is contributed by suresh07 
 
</script>


Output

2

Time complexity : O( 10^6) 
Auxiliary Space : O(1) 

 



Similar Reads

Placement of magical box on road to collect the maximum number of magical balls
There is a road which denotes the x-axis. Geek is at the start of the road (at origin). He has N magical balls. The balls are magical because they have a number written on them and they go that number of positions on every bounce. if the ball has 4 written on it, it goes to the positions like 4, 8, 12, 16, . . . . As Geek has N number of magical ba
8 min read
Find number of magical pairs of string of length L
A pair of string s and r are called magical if for every index i the character of s is less than r i.e. s[i] &lt; r[i]. The task is to count number of pairs of strings possible of length L. Since this value can be large, give answer modulo 109. Note: The string contains only lowercase English alphabets. Examples: Input: L = 1 Output: 325 Since the
5 min read
Replace minimal number of characters to make all characters pair wise distinct
Given a string consisting of only lowercase English alphabets. The task is to find and replace the minimal number of characters with any lower case character in the given string such that all pairs of characters formed from the string are distinct. If it is impossible to do so, print "IMPOSSIBLE". Note: If there is more than one answer possible, pr
10 min read
Magical Indices in an array
Given an array A of integers. Index i of A is said to be connected to index j if j = (i + A[i]) % n + 1 (Assume 1-based indexing). Start traversing array from index i and jump to its next connected index. If on traversing array in the described order, index i is again visited then index i is a magical index. Count the number of magical indexes in t
10 min read
Make a lexicographically smallest palindrome with minimal changes
Given a string S. Print the lexicographically smallest string possible. You can make minimal changes to the characters in the string and you can permute the string. Examples: Input : S = "aabc" Output : "abba" Input : S = "aabcd" Output : "abcba" Explanation 1:Change the last index "c" to "b", it becomes "aabb". Then rearrange the string, it become
11 min read
Minimal product subsequence where adjacent elements are separated by a maximum distance of K
Given an array arr[] and an integer K, the task is to find out the minimum product of a subsequence where adjacent elements of the subsequence are separated by a maximum distance of K.Note: The subsequence should include the first and the last element of the array. Examples: Input: arr[] = { 1, 2, 3, 4 }, K = 2 Output: 8 The first element in the su
10 min read
Find side of Square which makes minimal area to fit two identical rectangles inside it
Given height H, and width W, of a rectangle, the task is to find the side of a square of the minimum area in which two rectangles fit completely. Note: Two rectangles can touch each other by side or corner.Rectangles cannot intersect each other.Rectangles can also touch the sides of the square but must be completely inside it.The Rectangles can be
12 min read
Minimal distance such that for every customer there is at least one vendor at given distance
Given N and M number of points on the straight line, denoting the positions of the customers and vendors respectively. Each vendor provides service to all customers, which are located at a distance that is no more than R from the vendor. The task is to find minimum R such that for each customer there is at least one vendor at the distance which is
7 min read
Purchase in minimal cost
A person has a list of N items to buy. The cost of the ith item is represented by Pi. He also has M coupons. Each coupon can be used to purchase an item from the list whose cost is at least Li, with a discount of Di. Each coupon can only be used once, and multiple coupons cannot be used for the same item. Find the minimum total cost required to pur
13 min read
CSES Solutions - Minimal Rotation
A rotation of a string can be generated by moving characters one after another from beginning to end. For example, the rotations of acab are acab, caba, abac, and baca. Your task is to determine the lexicographically minimal rotation of a string. Examples: Input: s = "acab"Output: abacExplanation: All possible rotations are: "acab", "caba", "abac"
7 min read
Article Tags :
Practice Tags :