Arithmetic Expressions – HackerRank Solution Java , Python 3, Python 2 , C , C++, Best and Optimal Solutions , All you need.
Solutions of Algorithms Data Structures Hard HackerRank:
Here are all the Solutions of Hard , Advanced , Expert Algorithms of Data Structure of Hacker Rank , Leave a comment for similar posts
C++ replace HackerRank Solution
// Intention is a project that we can change with impunity
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
#include <fstream>
#include <string>
#include <map>
#include <set>
#include <memory>
#include <cstring>
#include <chrono>
#include <climits>
using namespace std;
#ifdef WIN32
#define INPUT my_file
const char* input_file_root = "Input";
const char* input_file_suffix = ".txt";
class OutputCompare
{
public:
~OutputCompare() {
if (use_file) {
if (problems == 0) {
cout << "Output identical to expected file\n";
}
else {
cout << "Output incorrect, found " << problems << " differences\n";
}
}
}
void set_file(const char* name) {
expected_file.open(name);
use_file = true;
}
OutputCompare& operator<<(char c) {
if (use_file) {
if (!iswspace(c)) {
char expected;
expected_file >> expected;
if (c != expected) {
cout << "Expected " << expected << " but program output was " << c << '\n';
++problems;
}
}
}
else {
cout << c;
}
return *this;
}
template <class T>
OutputCompare& operator<<(const T& value) {
if (use_file) {
T expected;
expected_file >> expected;
if (value != expected) {
cout << "Expected " << expected << " but program output was " << value << '\n';
++problems;
}
}
else {
cout << value;
}
return *this;
}
private:
ifstream expected_file;
int problems = 0;
bool use_file = false;
};
#define OUTPUT my_output_compare
#else
#define INPUT cin
#define OUTPUT cout
#define _ASSERT(x)
#endif
int main(int argc, const char * argv[])
{
// Read in problem
#ifdef WIN32
// Read from a file. Command line argument [1] is appended to the file name.
ifstream my_file;
string input_file_name(input_file_root);
if (argc >= 2) {
input_file_name.append(argv[1]);
}
input_file_name.append(input_file_suffix);
my_file.open(input_file_name);
OutputCompare my_output_compare;
if (argc < 3 || *argv[2] != 'x') {
string output_file_name("Output");
if (argc >= 3) {
output_file_name.append(argv[2]);
}
else if (argc >= 2) {
output_file_name.append(argv[1]);
}
output_file_name.append(".txt");
my_output_compare.set_file(output_file_name.c_str());
}
auto start_time = std::chrono::system_clock::now();
#endif
int n;
INPUT >> n;
int* data = new int[n];
char* operators = new char[n * 101];
char* follows = new char[n * 101];
for (int i = 0; i < n; ++i) {
INPUT >> data[i];
for (int j = 0; j < 101; ++j) {
operators[i * 101 + j] = ' ';
}
}
// Specify that the first input number can be reached
operators[data[0]] = '+';
for (int i = 1; i < n; ++i) {
char* last_ops = operators + (i - 1) * 101;
char* this_ops = operators + i * 101;
char* this_follows = follows + i * 101;
// See what numbers can be reached by combining numbers reachable after i-1 steps with data[i]
// Note that once we've found a solution, multiplying each later operand will give correct answer
// So we shortcircuit once entry 0 is filled in
for (int j = 0; j < 101 && this_ops[0] == ' '; ++j) {
if (last_ops[j] != ' ') {
int reachable = j + data[i];
reachable %= 101;
if (this_ops[reachable] == ' ') {
this_ops[reachable] = '+';
this_follows[reachable] = j;
}
reachable = j - data[i];
if (reachable < 0) reachable += 101;
if (this_ops[reachable] == ' ') {
this_ops[reachable] = '-';
this_follows[reachable] = j;
}
reachable = j * data[i];
reachable %= 101;
if (this_ops[reachable] == ' ') {
this_ops[reachable] = '*';
this_follows[reachable] = j;
}
}
}
}
// We should have a result (i.e. 0 should be included in last one)
if (operators[(n - 1) * 101] == ' ') {
OUTPUT << "ERROR!!!!!\n";
}
else {
// We obtain the result in reverse order
vector<char> result;
result.reserve(n);
int x = 0;
for (int i = n - 1; i > 0; --i) {
result.push_back(operators[i * 101 + x]);
x = follows[i * 101 + x];
}
_ASSERT(x == data[0]);
OUTPUT << data[0];
auto it = result.rbegin();
for (int i = 1; i < n; ++i, ++it) {
OUTPUT << (*it);
OUTPUT << data[i];
}
OUTPUT << '\n';
}
return 0;
#ifdef WIN32
my_file.close();
cout << "time=" << std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::system_clock::now() - start_time).count() << "ms\n";
#endif
return 0;
}
Java rep HackerRank Solution
import java.io.*;
import java.util.*;
public class Solution {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int[] a = new int[n];
for(int i = 0; i < n; i++) {
a[i] = sc.nextInt();
}
LinkedList<Character> sol = new LinkedList<Character>();
int[] inv = new int[101];
inv[1] = 1;
for(int i = 2; i <= 100; i++) {
for(int j=i; j <= 100; j++) {
if(((i*j)%101) == 1) {
inv[i] = j;
inv[j] = i;
}
}
}
backtrack(a,n-1,0,sol,inv);
while(sol.size() < n-1) {
sol.addFirst('*');
}
for(int i = 0; i < n-1; i++) {
System.out.print(a[i]+""+sol.get(i));
}
System.out.println(a[n-1]);
}
public static boolean backtrack(int[] a, int index, int mod, LinkedList<Character>sol, int[] inv) {
if(index == 0) {
return ((a[index] % 101) == mod);
}
if(a[index] == 0) {
if(mod == 0) {
sol.add('*');
return true;
}
} else {
if(mod == 0) {
if(backtrack(a,index-1,0,sol,inv)) {
sol.add('*');
return true;
}
} else {
if(backtrack(a,index-1,(mod*inv[a[index]])%101,sol,inv)) {
sol.add('*');
return true;
}
}
}
if(backtrack(a,index-1,(mod+a[index])%101,sol,inv)) {
sol.add('-');
return true;
}
int t = mod-a[index];
if(t < 0) {
t = t + 101;
}
if(backtrack(a,index-1,t,sol,inv)) {
sol.add('+');
return true;
}
return false;
}
}
Python 3 rep HackerRank Solution
import sys
sys.setrecursionlimit(15000)
ops = [lambda x,y: x + y, lambda x,y: x * y, lambda x,y: x - y]
op2s = ['+', '*', '-', '']
def exp(i, value, l):
if i == n:
return l if value % 101 == 0 else None
if len(cache[i]) > 0 and value in cache[i]:
return cache[i][value]
for k in range(3):
if exp(i + 1, ops[k](value, a[i]), l) != None:
l[i - 1] = k
cache[i][value] = l
return l
cache[i][value] = None
return None
n = int(input())
a = [int(x) for x in input().strip().split(' ')]
cache = [{}] * n
l = exp(1, a[0], [3] * n)
for i in range(n):
sys.stdout.write(str(a[i]))
sys.stdout.write(op2s[l[i]])
sys.stdout.flush()
Python 2 rep HackerRank Solution
# Enter your code here. Read input from STDIN. Print output to STDOUT
import itertools
N = int(raw_input().strip())
nums = map(int, raw_input().split())
seqs = itertools.product('*+-', repeat=N-1)
def get_seq(ops, n):
for op in ops:
x = n
for s in range(len(op)):
if op[s]=='+':
x = x + nums[s+1]
elif op[s]=='-':
x = x - nums[s+1]
else:
x = x * nums[s+1]
if x % 101 == 0:
return op
seq = get_seq(seqs,nums[0])
print ''.join([str(nums[0])]+[seq[i]+str(nums[i+1]) for i in range(len(seq))])
C rep HackerRank Solution
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
int main() {
int n;
scanf("%d", &n);
unsigned char * ops = malloc(n); // '+' - 1, '-' - 2, '*' - 3
memset(ops, 3, n);
int * nums = malloc(n * sizeof(unsigned int));
for (int i = 0; i < n; i ++) {
scanf("%d", &nums[i]);
}
unsigned char t[1000][101][2];
int i;
for (i = 0; i < n; i ++) {
if (0 == i) {
t[i][nums[i]][0] = 1;
t[i][nums[i]][1] = 1;
}
else {
int j;
for (j = 1; j < 101; j ++) {
if (t[i - 1][j][0]) {
int tmp = (j + nums[i]) % 101;
t[i][tmp][0] = j;
t[i][tmp][1] = 1;
if (0 == tmp) {
break;
}
tmp = (101 + j - nums[i]) % 101;
t[i][tmp][0] = j;
t[i][tmp][1] = 2;
if (0 == tmp) {
break;
}
tmp = (j * nums[i]) % 101;
t[i][tmp][0] = j;
t[i][tmp][1] = 3;
if (0 == tmp) {
break;
}
}
}
if (j < 101) {
break;
}
}
}
int p = 0;
for (int j = i; j > 0; j --) {
ops[j] = t[j][p][1];
p = t[j][p][0];
}
for (int i = 0; i < n - 1; i ++) {
printf("%d", nums[i]);
switch (ops[i + 1]) {
case 1:
printf("+");
break;
case 2:
printf("-");
break;
default:
printf("*");
break;
}
}
printf("%d\n", nums[n - 1]);
free(nums);
free(ops);
return 0;
}
Warmup
Implementation
Strings
Sorting
Search
Graph Theory
Greedy
Dynamic Programming
Constructive Algorithms
Bit Manipulation
Recursion
Game Theory
NP Complete
Debugging
Leave a comment below