8000 Added solution of Codewars/Binomial Expansion · Tamada4a/Algorithms@400534d · GitHub
[go: up one dir, main page]

Skip to content

Commit 400534d

Browse files
committed
Added solution of Codewars/Binomial Expansion
1 parent 35d1f22 commit 400534d

File tree

3 files changed

+171
-0
lines changed

3 files changed

+171
-0
lines changed
Lines changed: 117 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,117 @@
1+
public class KataSolution {
2+
3+
public static String expand(String expr) {
4+
// The corresponding values will be stored in these variables
5+
int n, a = Integer.MIN_VALUE, b = Integer.MIN_VALUE;
6+
char letter = ' ';
7+
8+
// We get the value of a, b, n and the letter of the expression
9+
StringBuilder sb = new StringBuilder();
10+
for (int i = 1; i < expr.length(); ++i) {
11+
if (expr.charAt(i) == '-' || isNumber(String.valueOf(expr.charAt(i)))) {
12+
sb.append(expr.charAt(i));
13+
} else if (isNumber(sb.toString()) || sb.toString().equals("-")) {
14+
if (sb.toString().equals("-"))
15+
sb.append("1");
16+
17+
if (a == Integer.MIN_VALUE) {
18+
a = Integer.parseInt(sb.toString());
19+
letter = expr.charAt(i);
20+
} else
21+
b = Integer.parseInt(sb.toString());
22+
23+
sb.setLength(0);
24+
}
25+
}
26+
// If the coefficient a == 1, then we adjust the values
27+
if (b == Integer.MIN_VALUE) {
28+
b = a;
29+
a = 1;
30+
letter = expr.charAt(1);
31+
}
32+
// We get the value of the degree
33+
n = Integer.parseInt(sb.toString());
34+
35+
// If the coefficient b == 0, then we return the result of the expression (a*letter)^n
36+
if (b == 0)
37+
return getPolyUnit(1, n, 0, a, b, letter, true);
38+
39+
// If the degree is == 0, then return 1
40+
if (n == 0)
41+
return "1";
42+
43+
sb.setLength(0);
44+
45+
// Otherwise, we calculate the value of each term of the polynomial using Pascal's triangle
46+
long nFac = getFactorial(n);
47+
for (int k = 0; k < n + 1; ++k) {
48+
// Calculate the coefficient C_n^k
49+
long c = nFac / (getFactorial(k) * getFactorial(n - k));
50+
51+
// If the leading element is missing + before the number
52+
if (sb.isEmpty()) {
53+
sb.append(getPolyUnit(c, n, k, a, b, letter, true));
54+
} else
55+
sb.append(getPolyUnit(c, n, k, a, b, letter, false));
56+
}
57+
58+
return sb.toString();
59+
}
60+
61+
62+
// The method allows you to determine whether a sequence is a number
63+
private static boolean isNumber(String str) {
64+
try {
65+
Integer.parseInt(str);
66+
return true;
67+
} catch (Exception e) {
68+
return false;
69+
}
70+
}
71+
72+
73+
// The method allows you to get the factorial of a number
74+
private static long getFactorial(int f) {
75+
long result = 1;
76+
for (long i = 1; i <= f; i++) {
77+
result = result * i;
78+
}
79+
return result;
80+
}
81+
82+
83+
// The method allows you to get a correct representation of the next term of the polynomial
84+
private static String getPolyUnit(long c, int n, int k, int a, int b, char letter, boolean isLead) {
85+
StringBuilder result = new StringBuilder();
86+
87+
// We raise the coefficients a and b to the appropriate degrees
88+
long newA = (long) Math.pow(a, n - k);
89+
long newB = (long) Math.pow(b, k);
90+
91+
// If the product is different from zero
92+
if (c * newA * newB != 0) {
93+
// If the coefficient of a non-leading element is positive
94+
if (c * newA * newB > 0 && !isLead)
95+
result.append("+%d".formatted(c * newA * newB));
96+
// If the coefficient in front of the leading element == -1
97+
else if (c * newA * newB == -1 && isLead)
98+
result.append("-");
99+
// If the value of the coefficient modulus is != 1 or the last element is being processed
100+
else if (Math.abs(c * newA * newB) != 1 || n - k == 0)
101+
result.append(c * newA * newB);
102+
}
103+
104+
// Processing the display of the letter in the expression. It is present in the expression if
105+
// the coefficient is not zero, or it is not the last element
106+
if (n - k != 0 && c * newA * newB != 0) {
107+
// If the last element is added, add a letter without a degree
108+
if (n - k == 1)
109+
result.append(letter);
110+
// Otherwise, with a degree
111+
else
112+
result.append("%s^%d".formatted(letter, n - k));
113+
}
114+
115+
return result.toString();
116+
}
117+
}

Codewars/Binomial Expansion/README.md

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
# Binomial Expansion
2+
3+
## DESCRIPTION:
4+
The purpose of this kata is to write a program that can do some algebra.
5+
6+
Write a function `expand` that takes in an expression with a single, one character variable, and expands it. The expression is in the form
7+
`(ax+b)^n` where `a` and `b` are integers which may be positive or negative, `x` is any single character variable, and `n` is a natural number.
8+
If a = 1, no coefficient will be placed in front of the variable. If a = -1, a "-" will be placed in front of the variable.
9+
10+
The expanded form should be returned as a string in the form `ax^b+cx^d+ex^f...` where `a`, `c`, and `e` are the coefficients of the term, `x`
11+
is the original one character variable that was passed in the original expression and `b`, `d`, and `f`, are the powers that `x` is being raised
12+
to in each term and are in decreasing order.
13+
14+
If the coefficient of a term is zero, the term should not be included. If the coefficient of a term is one, the coefficient should not be
15+
included. If the coefficient of a term is -1, only the "-" should be included. If the power of the term is 0, only the coefficient should be
16+
included. If the power of the term is 1, the caret and power should be excluded.
17+
18+
## Examples:
19+
```java
20+
KataSolution.expand("(x+1)^2"); // returns "x^2+2x+1"
21+
KataSolution.expand("(p-1)^3"); // returns "p^3-3p^2+3p-1"
22+
KataSolution.expand("(2f+4)^6"); // returns "64f^6+768f^5+3840f^4+10240f^3+15360f^2+12288f+4096"
23+
KataSolution.expand("(-2a-4)^0"); // returns "1"
24+
KataSolution.expand("(-12t+43)^2"); // returns "144t^2-1032t+1849"
25+
KataSolution.expand("(r+0)^203"); // returns "r^203"
26+
KataSolution.expand("(-x-1)^2"); // returns "x^2+2x+1"
27+
```
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
# Биномиальное разложение
2+
3+
## Описание:
4+
Цель этого ката - написать программу, которая может выполнять некоторые алгебраические операции.
5+
6+
Напишите функцию `expand`, которая принимает выражение с одной-единственной символьной переменной и раскладывает его. Выражение имеет вид
7+
`(ax+b)^n`, где `a` и `b` - целые числа, которые могут быть положительными или отрицательными, `x` - любая односимвольная переменная, а `n` -
8+
натуральное число. Если a = 1, то перед переменной не будет поставлен коэффициент. Если a = -1, то перед переменной будет поставлен знак "-".
9+
10+
Развернутая форма должна быть возвращена в виде строки в виде `ax^b+cx^d+ex^f...`, где `a`, `c` и `e` являются коэффициентами соответствующих
11+
членов выражения, `x` - исходная односимвольная переменная, которая была передана в исходное выражение, `b`, `d` и `f` - это степени, в которые
12+
`x` возводится в каждом члене, и они расположены в порядке убывания.
13+
14+
Если коэффициент члена равен нулю, то этот член не следует включать в итоговое выражения. Если коэффициент члена равен единице, то этот
15+
коэффициент включать не следует. Если коэффициент члена равен -1, то следует включать только "-". Если степень члена равна 0, то должен быть
16+
включен только коэффициент. Если степень члена равна 1, то циркумфлекс (^) и степень должны быть исключены.
17+
18+
## Примеры:
19+
```java
20+
KataSolution.expand("(x+1)^2"); // возвращает "x^2+2x+1"
21+
KataSolution.expand("(p-1)^3"); // возвращает "p^3-3p^2+3p-1"
22+
KataSolution.expand("(2f+4)^6"); // возвращает "64f^6+768f^5+3840f^4+10240f^3+15360f^2+12288f+4096"
23+
KataSolution.expand("(-2a-4)^0"); // возвращает "1"
24+
KataSolution.expand("(-12t+43)^2"); // возвращает "144t^2-1032t+1849"
25+
KataSolution.expand("(r+0)^203"); // возвращает "r^203"
26+
KataSolution.expand("(-x-1)^2"); // возвращает "x^2+2x+1"
27+
```

0 commit comments

Comments
 (0)
0