I am new to java8. Just wanted to know, this is correct way to write java 8 and suggest if given code can be improved further with respect to java8 functional programming?
public class OperationByJava8 {
public int add(int a, int b) {
Operation op = (num1, num2) -> num1 + num2;
return op.operate(a, b);
}
public int subtract(int a, int b) {
Operation op = (num1, num2) -> num1 - num2;
return op.operate(a, b);
}
public int multiply(int a, int b) {
Operation op = (num1, num2) -> num1 * num2;
return op.operate(a, b);
}
public int devide(int a, int b) {
Operation op = (num1, num2) -> {
if (num2 == 0) {
throw new IllegalArgumentException("denominator cannot be zero");
}
return num1 / num2;
};
return op.operate(a, b);
}
public static void main(String[] args) {
OperationByJava9 op = new OperationByJava9();
System.out.println(" Addition(12, 12) :" + op.add(12, 12));
System.out.println(" Subtract(12, 12) :" + op.subtract(12, 12));
System.out.println(" Multiply(12, 12) :" + op.multiply(12, 12));
System.out.println(" Devide (12, 12) :" + op.devide(12, 12));
}
}
#FunctionalInterface
interface Operation {
int operate(int a, int b);
}
Your approach is completely fine and would be good to proceed with.
if you want to further reduce the code, you could create a single function as follows for addition, subtraction and multiplication.
public int apply(int a, int b, IntBinaryOperator func) {
return func.applyAsInt(a, b);
}
but then you'll need to create a separate function for the division functionality in order to throw the IllegalArgumentException exception in the case of the second argument being 0.
Note that i've used the IntBinaryOperator functional interface to avoid having to create the Operation interface but if the latter is more meaningful then you can keep that.
Alternatively, you can define the functions inline and then invoke them:
IntBinaryOperator add = (num1, num2) -> num1 + num2;
IntBinaryOperator subtract = (num1, num2) -> num1 + num2;
IntBinaryOperator multiply = (num1, num2) -> num1 + num2;
IntBinaryOperator division = (num1, num2) -> {
if (num2 == 0)
throw new IllegalArgumentException("denominator cannot be zero");
return num1 / num2;
};
System.out.println(" Addition(12, 12) :" + add.applyAsInt(12, 12));
System.out.println(" Subtract(12, 12) :" + subtract.applyAsInt(12, 12));
System.out.println(" Multiply(12, 12) :" + multiply.applyAsInt(12, 12));
System.out.println(" Devide (12, 12) :" + division.applyAsInt(12, 12));
Related
I'm gonna crazy everything is looking good where is the problem?
void main(){
int num1 = 10;
int num2 = 11;
print("First : $num1, $num2");
swap(num1,num2);
print("Last : $num1, $num2");
}
void swap(int num1,int num2){
int temp;
temp = num1;
num1 = num2;
num2 = temp;
}
MY OUTPUT:
First: 10,11
Last: 10,11
You should try removing the swapping from the swap function and place it directly inside the main function. When calling functions, references to the variables' values are passed and not the variable itself.
#Ketan Ramteke is right. Or you can return a list and use that value like this:
void main(){
int num1 = 10;
int num2 = 11;
print("First : $num1, $num2");
List arr = swap(num1,num2);
print("Last : ${arr[0]}, ${arr[1]}");
}
List swap(int num1,int num2){
int temp;
temp = num1;
num1 = num2;
num2 = temp;
return [num1, num2];
}
// Dart 2.6.
void main(){
int num1 = 10;
int num2 = 11;
print("First : $num1, $num2");
// get returned swapped values
List result = swap(num1,num2);
// assign them to original variables
num1 = result[0];
num2 = result[1];
//print the mutated num1 and num2
print("Last : $num1, $num2");
}
List swap(int num1,int num2){
int temp;
temp = num1;
num1 = num2;
num2 = temp;
// print("Last : $num1, $num2");
return [num1, num2];
}
The Magical Sequence
A Magical Sequence is defined as shown.
Magical[1] = 0
Magical[2] = 1
Magical[n] = Magical[n-1] + 2*Magical[n-2] + 3*Magical[n-3] + ... (n-1)*Magical[1] + n*1., for n > 2
Given n (1 <= n <= 10^9 ), find Magical[n].
Example 1: input: 3
Output: 4
Explanation:
Magical[n] = 1*Magical[n-1] + 2*Magical[n-2] + 3*1
Magical[3] = 1*Magical[2] + 2*Magical[1] + 3*1
Magical[3] = 1*1 + 2*0 + 3*1
Magical[3] = 4
Example 2: input: 4
Output: 10
Magical[4] = 1*Magical[3]+2*Magical[2]+3*Magical[1]+4*1
= 1*4+2*1+3*0+4 = 10
Example 3: input: 5
Output: 26
Magical[5] = 1*Magical[4]+2*Magical[3]+3*Magical[2]+4*Magical[1]+5*1
= 1*10+2*4+3*1+4*0+5 = 26
I tried something like below :-
int CuckooNum(int n)
{
if (1 == n)
{
return 0;
}
else if (2 == n)
{
return 1;
}
std::vector<int> vec;
vec.resize(n);
vec[0] = 4;
vec[1] = 0;
vec[2] = 1;
int multiplyer = n;
int result = 0;
for (int index=3; index <= n; index++)
{
result += multiplyer * vec[index-1];
vec[index] = result;
multiplyer--;
}
return result;
}
long long func(int n)
{
if (n==1) return 0;
else if (n==2) return 1;
else return 1*func(n-1)+2*func(n-2)+n;
}
As the size n can be very large (10^9), a direct implementation O(n^2) is not possible.
A specific algorithm is needed. I will focus here on the algorithm, and propose a O(log n) solution.
To simplify explanation, I rename magical[] as x[]
Moreover, we can define x[0] = 1. Then,
x[n] = x[n-1] + 2*x[n-2] + 3*x[n-3] + ... (n-1)*x[1] + n*x[0]
As
x[n-1] = 1*x[n-2] + 2*x[n-3] + ... (n-2)*x[1] + (n-1)*x[0]
It follows
x[n] - x[n-1] = x[n-1] + x[n-2] + x[n-3] + ... x[1] + x[0] = S[n-1]
When S[n] represents the sum of the terms until n (x[0] included)
Moreover,
S[n] = S[n-1] + x[n] = 2*S[n-1] + x[n-1]
Therefore, the iterative formula can be represented in a simple matrix form:
(x[n]) = (1 1) (x[n-1])
(S[n]) (1 2) (S[n-1])
Or, defining the vector (x[n] S[n])^t as Z[n]:
Z[n] = A * Z[n-1] where A is the matrix (1 1)
(1 2)
Note: this formula is valid for n>= 4 only, as the first x[n] values do no respect the simple recurrence relation.
It follows that
Z[n] = A^(n-3) Z[3] with Z[3] = (4 6)^t
Classically, this calculation can be performed with O(log n) complexity, iteratively calculating A^2, A^4, A^8 etc.
Pay attention that the values increase rapidly.
Here is an example of C++ implementation. Note that this implementation is not optimized, as for example it doesn't use the fact that all matrices are symmetric.
#include <iostream>
#include <array>
using Matr22 = std::array<std::array<long long int, 2>, 2>;
using Vect2 = std::array<long long int, 2>;
Matr22 Matrsquare (const Matr22 &m) {
Matr22 m2;
m2[0][0] = m[0][0]*m[0][0] + m[0][1]*m[1][0];
m2[0][1] = m[0][0]*m[0][1] + m[0][1]*m[1][1];
m2[1][0] = m[1][0]*m[0][0] + m[1][1]*m[1][0];
m2[1][1] = m[1][0]*m[0][1] + m[1][1]*m[1][1];
return m2;
}
Matr22 Mult (const Matr22 &m1, const Matr22 &m2) {
Matr22 y;
y[0][0] = m1[0][0]*m2[0][0] + m1[0][1]*m2[1][0];
y[0][1] = m1[0][0]*m2[0][1] + m1[0][1]*m2[1][1];
y[1][0] = m1[1][0]*m2[0][0] + m1[1][1]*m2[1][0];
y[1][1] = m1[1][0]*m2[0][1] + m1[1][1]*m2[1][1];
return y;
}
Vect2 Mult (const Matr22 &m, const Vect2& x) {
Vect2 y;
y[0] = m[0][0] * x[0] + m[0][1] * x[1];
y[1] = m[1][0] * x[0] + m[1][1] * x[1];
return y;
}
// Matrix exponentiation
Matr22 Mult_exp (const Matr22 &m, int exp) {
Matr22 y = {1, 0, 0, 1};
if (exp == 0) return y;
Matr22 M2k = m;
while (exp) {
if (exp%2) y = Mult (y, M2k);
M2k = Matrsquare (M2k);
exp /= 2;
};
return y;
}
long long int Magical (int n) {
if (n == 1) return 0;
if (n == 2) return 1;
if (n == 3) return 4;
Matr22 A = {1, 1, 1, 2};
Vect2 z = {4, 6}; // corresponds to n=3
auto Ak = Mult_exp (A, n-3);
z = Mult (Ak, z);
return z[0];
}
int main() {
int n;
std::cout << "Input n: ";
std::cin >> n;
auto ans = Magical (n);
std::cout << "Magical[" << n << "] = " << ans << '\n';
}
I haven't been able to come up with a bullet proof answer to this question. My solution fails few cases. I would appreciate some insights.
Question:
Given two strings A and B, return the number of times A needs to be stated such that it contains string B?
Example #1:
String A : abcd
String B : cdabcdab
Should return 3 because:
abcdabcdabcd ( A repeated 3 times)
cdabcdab ( B is contained in now)
Example #2:
String A = abcd
String B = d
should return 1 because B is already a substring of A.
Example #3:
String A = abcd
String B = cda
Should return 2 because:
abcdabcd
cda
Example #4:
String A = abcd
String B = cdb
Should return -1, it doesn't matter how many times we state A, there is no way we can produce B.
Few insights I have noticed:
Order of characters matter
A must contain at least all the
characters in B
Neither A or B needs to be a substring of the
other.
There must be an overlap between the end of one string and
the beginning of the other.
If |B| > 2|A| - 2 and B occurs in A^n, then A occurs in B. Count and remove all complete instances of A in B, and then the solution is this count plus the solution to the same problem with A's removed from B.
Otherwise, it is guaranteed that if B appears in A^n, it appears in A^3. Construct A^3 and find the first occurrence of B in it. Find and remove any complete instances of A appearing after the end of B's appearance in A^3. Return 3 minus the number of removed instances.
Examples:
f(abcd, cdabcdab)
|cdabcdab| > 2|abcd| - 2 since 8 > 2*4 - 2
^^^^
first instance of A in B; no more, so return 1 + f(cdab, abcd) = 3
f(cdab, abcd)
|cdab| < 2|abcd| - 2 since 4 < 2*4 - 2
abcdabcdabcd
^^^^
first instance of B in A; one instance of A after B, so return 3 - 1 = 2.
f(d, abcd)
|d| < 2|abcd| - 2, since 1 < 2*4 - 2
abcdabcdabcd
^
first instance of B in A; two instances of A after B, so return 3 - 2 = 1.
f(cda, abcd)
|cda| = 2|abcd| - 2 since 3 = 2*4 - 2
abcdabcdabcd
^^^
first instance of B in A; one instance of A after B, so return 3 - 1 = 2.
f(cdb, abcd)
|cbd| = 2|abcd| - 2 since 3 = 2*3 - 2
abcdabcdabcd
^ no instances of B in A; return -1.
Some minor optimizations include:
if |B| = 0, return 0.
if |B| = 1, use A^1 instead of A^3.
if |B| < |A| + 2, use A^2 instead of A^3.
One way to do it as like the code segment below. I noticed that no matter how many times we duplicate string A, this number (of times) can't be greater than length of string B. I hope this helps. Please note my answer runs in O(N^2) time. Not Ideal but any brute force solution should give you a good start towards the optimum/final solution.
string A = "abcd";
string B = "cda";
int i = 1;
string S = A;
while (i < B.Length)
{
S = S + A;
i++;
if(S.Contains(B))
break;
}
if(i==B.Length-1 && !S.Contains(B))
Console.WriteLine(-1); //not found
Console.WriteLine(i); //the solution
#include <iostream>
#include <string>
using namespace std;
int main()
{
string a,b,s="";
cin>>a>>b;int count=0;
size_t f = a.find(b);
if(f==string::npos)
{
for(int i=0;i<b.length() && s.find(b)==string::npos;++i)
{
s.append(a);
count++;
}
}
else
{
cout<<1<<endl;
return 0;
}
if(s.find(b)!=string::npos)
cout<<count;
else
cout<<0<<endl;
return 0;
}
If A is longer than B then return 1 if B is in A.
if A is same length as B and they are equal return 1.
Look for the location in which B contains A, with a wrap around.
So A is abc and B is bca you will find that A is in B starting at [2]. Then start covering B with A starting with that location and count how many times you had to repeat A. Note that if covering fails, you need to keep searching for other possible places where A is in B.
it is guaranteed that if B appears in A^n, it appears in A^3.
So writing simple Java Code :
import java.io.*;
public class StringDemo {
public static void print(String x){
System.out.println(x);
}
public static void main(String args[]) {
String A = "abcd";
int alen = A.length();
String B = "cda";
int blen = B.length();
String C = A+A+A;
int op = -1;
if (C.indexOf(B) > -1 ){
op = 3;
C = C.substring(0,alen*2);
if (C.indexOf(B) > -1){
op = 2;
C = C.substring(0,alen);
if (C.indexOf(B) > -1){
op = 1;
}
}
}
print(Integer.toString(op));
}
}
There is a similar question I solved few days ago.
The Question :
Given two strings A and B, find the minimum number of times A has to be repeated such that B is a substring of it. If no such solution, return -1.
For example, with A = "abcd" and B = "abcdabcd".
Return 3, because by repeating A three times (“abcdabcdabcd”), B is a substring of it; and B is not a substring of A repeated two times ("abcdabcd").
One probable solution from my side can be this:
public class test1 {
public static void main(String[] args) {
String a = " abcd";
String b = "abcdabcd";
System.out.println(fix(a,b));
}
public static int fix(String a,String b) {
StringBuffer sbr = new StringBuffer(a);
int c = 1 ;
//for( ; sbr.length() < b.length() ; c++ ) {sbr.append(a) ; }
while(sbr.length() < b.length() ) {
sbr.append(a);
c++ ;
}
String t = sbr.toString();
// if str1 not contains then we can concatenate and we must increase the count
if(!t.contains(b)) {
t += a ;
c++ ;
}
if(t.contains(b)) {
c++ ;
}
return c ;
}
}
The output will be 3 .abcdabcdabcd => 3 times abcd then abcdabcd will be a substring of it. That's why answer 3 is correct. If str1 has str2 the we increment the count by 1.
My solution is naive, but I think it works fine. If anyone found a flaw in this, please let me know.
private static int countRepeatOfString(StringBuffer concatenate, String a, String b) {
if (concatenate.length() == 0 || b.length() == 0) {
return -1;
}
int maxConcatenateCount;
/* For cases like:
String A - abcd (length=4) Longest possible would be:
String B - cdabcdab (length=8) abcdabcdabcd
Let r = the ratio of String B length to String A length
r + 2 is for taking care of case:
String A - abc
String B - c(abc)a
*/
if (a.length() <= b.length()) {
maxConcatenateCount = b.length() / a.length() + 2;
return countOccurrence(maxConcatenateCount, concatenate, a, b);
} else {
return countOccurrence(2, concatenate, a, b);
}
}
private static int countOccurrence(int maxConcatenateCount, StringBuffer concatenate, String a, String b) {
boolean found = false;
int currentConcatenateCount = 1;
int repeatCount = 1;
while (currentConcatenateCount <= maxConcatenateCount) {
int index = concatenate.indexOf(b, 0);
if (index != -1) {
found = true;
break;
}
concatenate.append(a);
currentConcatenateCount++;
repeatCount++;
}
if (found) {
return repeatCount;
} else {
return -1;
}
}
Taking the solution from #Patrick87
Here is the code:
public class ATimesToContainB {
public static void main(String args[]) {
System.out.println();
String a = "abcd";
String b = "cdabcdabcdabcdab";
System.out.println("Brute Force Multiply A :" + a + " n= " + atimesbBruteForce(a, b) + " to contain B " + b);
System.out.println("Optimized Multiply A :" + a + " n= " + atimesb(a, b) + " to contain B " + b);
System.out.println();
a = "abcd";
b = "cdabcdabcdabcdabab";
System.out.println("Brute Force Multiply A :" + a + " n= " + atimesbBruteForce(a, b) + " to contain B " + b);
System.out.println("Optimized Multiply A :" + a + " n= " + atimesb(a, b) + " to contain B " + b);
System.out.println();
a = "abcd";
b = "cdabcdab";
System.out.println("Brute Force Multiply A :" + a + " n= " + atimesbBruteForce(a, b) + " to contain B " + b);
System.out.println("Optimized Multiply A :" + a + " n= " + atimesb(a, b) + " to contain B " + b);
System.out.println();
a = "abcd";
b = "d";
System.out.println("Brute Force Multiply A :" + a + " n= " + atimesbBruteForce(a, b) + " to contain B " + b);
System.out.println("Optimized Multiply A :" + a + " n= " + atimesb(a, b) + " to contain B " + b);
System.out.println();
a = "abcd";
b = "cda";
System.out.println("Brute Force Multiply A :" + a + " n= " + atimesbBruteForce(a, b) + " to contain B " + b);
System.out.println("Optimized Multiply A :" + a + " n= " + atimesb(a, b) + " to contain B " + b);
System.out.println();
a = "abcd";
b = "cdb";
System.out.println("Brute Force Multiply A :" + a + " n= " + atimesbBruteForce(a, b) + " to contain B " + b);
System.out.println("Optimized Multiply A :" + a + " n= " + atimesb(a, b) + " to contain B " + b);
}
//O(n*m^2)
private static int atimesbBruteForce(String a, String b) {
int n = a.length();
int m = b.length();
String tempA = a;
if (tempA.contains(b))
return 1;
for (int i = 1; i < m; i++) { // O(m)
tempA = tempA + a;
if (tempA.contains(b)) //O(n*m); since temp A length could be max "m" times a length which is "n", for checking contains it take O(textLength); O(m*n)
return i + 1;
}
return Integer.MIN_VALUE;
}
//Idea take from above stack overflow
//O((m^2)/n) -> i hope its right
private static int atimesb(String a, String b) {
int n = a.length();
int m = b.length();
if (m == 0)
return 0;
if (m == 1)
return (a.contains(b) ? 1 : -1);
int count;
if (m > 2 * n - 2) {
count = countTimes(b, a); // O(m/n)
if (count > 0) {
return count + atimesb(a, removeByTimes(b, a)); // O(m)
} else
return count;
} else if (m < n + 2) {
a = a + a;
count = countTimes(a, b); // O(m)
if (count > 0) {
return 1 + count;
} else
return Integer.MIN_VALUE;
} else {
a = a + a + a;
count = countTimes(a, b); // O(m)
if (count > 0)
return 3 - count;
else return Integer.MIN_VALUE;
}
}
private static String removeByTimes(String b, String a) {
return b.replaceAll(a, "");
}
/**
* It will count how many times "toCount" is occur in "fromCount" if occures at all
*
* #param fromToCount
* #param toCount
* #return How many times, otherwise 0 if not occur
*/
private static int countTimes(String fromToCount, String toCount) {
int count = 0;
while (fromToCount.contains(toCount)) {
fromToCount = fromToCount.replaceFirst(toCount, "");
count++;
}
return count;
}
}
Here is my solution in Python2 for the same. I followed mathematical way of solving the expression
def google(a,b):
x=(len(b)/len(a))+1
print x
google("abcd","cda")
I'm trying to make a program that finds the sum of all the integers between two numbers, inclusive. I'll paste what I have so far, but I'm getting an error (i is a duplicate local variable?). Thanks
public int sum(int num1, int num2){
if (num1 == num2){
return num1;
}
if (num1 > num2){
for (int i = (num2 + 1), i <= num1, i++){
num2 += i;
}
return num2;
}
if (num2 > num1){
for(int i = num1 + 1, i <= num2, i++){
num1 += i;
}
return num1;
}
}
Use semi-colons in your for loops, not commas:
public int sum(int num1, int num2){
if (num1 == num2){
return num1;
}
if (num1 > num2){
for (int i = (num2 + 1); i <= num1; i++){
num2 += i;
}
return num2;
}
if (num2 > num1){
for(int i = num1 + 1; i <= num2; i++){
num1 += i;
}
return num1;
}
}
whats the logic for calculating HCF of given numbers?
The usual way to calculate the highest common factor, more commonly called the greatest common divisor, is Euclid's algorithm.
If you want to calculate the HCF of more than two numbers, say i1, i2, i3, ..., in, one algorithm is:
res = gcd(i[1], i[2])
for j = 3..n do
res = gcd(res, i[j])
end
return res
Here's an implementation of Euclid's algorithm in C++:
unsigned int hcf(unsigned int a, unsigned int b) {
if (b == 0) {
return a;
} else {
return hcf(b, a % b);
}
}
A faster and shorter code for GCD
int gcd(int a, int b) {
while(b) b ^= a ^= b ^= a %= b;
return a;
}
Here is the code to calculate the H.C.F of two integers
If you have any problem comment your query, feel free to ask
import java.util.*;
class ABC{
int HCF(int a,int b){
int c;
int d;
c=a%b;
if(c==0)
return b;
else
return HCF(b,c);
}
public static void main(String[]args){
int a,b;
Scanner sc = new Scanner(System.in);
System.out.println("Enter your first number: ");
a= sc.nextInt();
System.out.println("Enter your second number: ");
b=sc.nextInt();
ABC obj= new ABC();
if(b>a)
System.out.println("Wrong Input the first number must be larger than the second one");
else
System.out.println("The H.C.F of "+a+" and "+b+" is: "+obj.HCF(a,b));
}
In this way, it will work no matter the order of the input:
public static void main(String[] args) {
int a, b;
Scanner sc = new Scanner(System.in);
System.out.println("Enter your first number: ");
a = sc.nextInt();
System.out.println("Enter your second number: ");
b = sc.nextInt();
System.out.println("The H.C.F of " + a + " and " + b + " is: " + HCF(a,b));
}
private static int HCF(int a, int b) {
int c;
if (a > b) {
c = a % b;
if (c == 0)
return b;
else
return HCF(b, c);
} else {
c = b % a;
if (c == 0)
return a;
else
return HCF(a, c);
}
}
while(b):
a, b = b, a % b
print("HCF/GCD is:",a)
This would give answer.