I'm trying to calculate the number of rCombinations for a project for school and I can't seem to get my method to return the correct values.
I talked to my professor and he recommended canceling the common factors in factorials. Such that
35!/32! = 35*34*33.
This is what I have so far.
public static long rCombinations(int n, int r) {
int q = n-r;
long x = 1;
for(int i = r; i <= r; i ++)
{
x = n*(n-i);
}
return x/factorial(r);
}
You can use this implementation for calculating large factorial of numbers without BigInteger as follows :
import java.util.Scanner;
public class N_Faktorial {
public static void main(String[] args) {
int u = 1, A[] = new int[9999999];
Scanner scan = new Scanner(System.in);
System.out.print("n=");
int n = scan.nextInt();
A[1] = 1;
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= n; j++) {
A[j] *= i;
}
for (int j = 1; j <= n; j++) {
if (A[j] > 9) {
A[j + 1] += A[j] / 10;
A[j] %= 10;
}
if (A[u + 1] != 0) {
u++;
}
}
}
for (int i = u; i >= 1; i--) {
System.out.print(A[i]);
}
//when n>=24 count of digit of n! is equal to n+1.
System.out.println("\n Result : " + n + " count of digit " + u);
}
}
After this you need some solution for doing division operation.
Hope it helps!.
For n!/m!, where n >= m
int out = 1;
for(int i = n; i <= m; i++)
out *= i;
For n!/m!, where n <= m
double out = 1;
for(int i = n; i <= m; i++)
out /= i;
In both cases, out = n!/m!
Note that it's still easy to overflow an int, 55!/49! is too big
Related
I have a factorial function on my program that works fine until i try to execute the function deleteRepeated(), the console is telling me that the error is in the return of the factorial function, maybe it's being called by a single function too many times in a short period of time? I've been stuck for hours.
import java.util.Scanner;
public class ex9 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int[] arr = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = sc.nextInt();
}
int[] newArr = new int[n - repeated(arr)];
int[] finalArr = deleteRepeated(arr, newArr);
for (int a : finalArr) {
System.out.println(a);
}
}
public static long factorial(int n) {
if (n == 0)
return 1;
return (n * factorial(n - 1));
}
public static int repeated(int arr[]) {
int n = arr.length;
int mix = (int) (factorial(n) / (2 * factorial(n - 2)));
int i = 0;
int k = 0;
int rep = 0;
int a = -100;
while (i < mix) {
for (int j = k + 1; j < n; j++) {
if (arr[k] == arr[j] && a != j) {
a = j;
rep += 1;
}
i++;
}
k++;
}
return rep;
}
public static int[] deleteRepeated(int arr[], int newArr[]) {
int n = arr.length;
int rep = repeated(arr);
int i = 0;
int k = 0;
int a = -100;
while (i < newArr.length) {
for (int j = k + 1; j < n; j++) {
if (arr[k] == arr[j] && a != arr[k]) {
a = arr[j];
newArr[k] = arr[k];
}
i++;
}
k++;
}
rep = repeated(newArr);
if (rep > 0) {
int[] newArr2 = new int[newArr.length - rep];
deleteRepeated(newArr, newArr2);
}
return newArr;
}
}
Only thing i could do to avoid the error was stopping the function from executing :/, maybe it has to do with how i'm re-calling it at the end of each execution...? is what i did allowed?
So, deleteRepeated is all messed up. The issue is deleteRepeated does not actually remove duplicate elements, so the check for the base case of recursion always fails. I'm not sure why you're using recursion here anyway; if the while loop worked properly, it could remove all duplicates without need for recursion.
It appears that you copy-pasted the implementation of repeated into deleteRepeated, and you replaced the logic for handling repeated elements with logic that handles non-repeated elements.
Here is how I would implement the method:
public static int deleteRepeated(int arr[], int newArr[]) {
int n = 0;
for(int i = 0; i < arr.length; i++) {
boolean unique = true;
for(int j = 0; j < n; j++)
unique = unique && newArr[j] != arr[i];
if(unique)
newArr[n++] = arr[i];
if(n >= newArr.length) break;
}
return n;
}
How to flip this triangle?
So i was making aritmethic sequance triangle. It was upside down.
How do I turn it 180 degree?
for example:
1=1
1+2=3
1+2+3=6
etc...
my code:
package javaapplication4;
public class NewClass5 {
public static void main(String[] args) {
int i=5,a;
for(int j=i; j>=1; j--) {
for(a=1; a<=i; a++)
System.out.print(a +" + ");
int n = 0;
for(a = 1; a<=i; a++) {
n = n + a;
}
System.out.print(" = "+ n);
System.out.println();
i--;
}
}
}
You can do it for any n, by getting input from the user
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
for (int i = 1; i <= n; i++) {
int add = 0;
for (int j = 1; j <= i; j++) {
System.out.print(j);
if (j == i)
System.out.print("=");
else
System.out.print("+");
add += j;
}
System.out.println(add);
}
I think you just need to change the sequence of loop from descending to ascending, rest of the things should be the same:
for (int i = 1; i <= 5; i++) {
int sum = 0;
for (int j = 1; j <= i; j++) {
System.out.print(j);
if (j == i)
System.out.print("=");
else
System.out.print("+");
sum += j;
}
System.out.println(sum);
}
When I run this, I'm able to see expected output:
src : $ java NewClass5
1=1
1+2=3
1+2+3=6
1+2+3+4=10
1+2+3+4+5=15
For my university assignment in java I have been asked to provide "extra analytics functions" I decided to use Levenshtein distance but I have an issue where the number outputted to the console is one less than the actual answer. So the distance between "cat" and "hat" should be 1 but it's displaying as 0
public class Levenshtein {
public Levenshtein(String first, String second) {
char [] s = first.toCharArray();
char [] t = second .toCharArray();
int Subcost = 0;
int[][] array = new int[first.length()][second.length()];
for (int i = 0; i < array[0].length; i++)
{
array[0][i] = i;
}
for (int j = 0; j < array.length; j++)
{
array [j][0]= j;
}
for (int i = 1; i < second.length(); i++)
{
for (int j = 1; j < first.length(); j++)
{
if (s[j] == t [i])
{
Subcost = 0;
}
else
{
Subcost = 1;
}
array [j][i] = Math.min(array [j-1][i] +1,
Math.min(array [j][i-1] +1,
array [j-1][i-1] + Subcost) );
}
}
UI.output("The Levenshtein distance is -> " + array[first.length()-1][second.length()-1]);
}
}
Apparently you're using the following algorithm:
https://en.wikipedia.org/wiki/Levenshtein_distance#Iterative_with_full_matrix
I think you were not too accurate with indices. I'm not sure where exactly the problem is, but here is a working version:
public int calculateLevenshteinDistance(String first, String second) {
char[] s = first.toCharArray();
char[] t = second.toCharArray();
int substitutionCost = 0;
int m = first.length();
int n = second.length();
int[][] array = new int[m + 1][n + 1];
for (int i = 1; i <= m; i++) {
array[i][0] = i;
}
for (int j = 1; j <= n; j++) {
array[0][j] = j;
}
for (int j = 1; j <= n; j++) {
for (int i = 1; i <= m; i++) {
if (s[i - 1] == t[j - 1]) {
substitutionCost = 0;
} else {
substitutionCost = 1;
}
int deletion = array[i - 1][j] + 1;
int insertion = array[i][j - 1] + 1;
int substitution = array[i - 1][j - 1] + substitutionCost;
int cost = Math.min(
deletion,
Math.min(
insertion,
substitution));
array[i][j] = cost;
}
}
return array[m][n];
}
I found this question in geeksforgeeks. It was asked in an amazon interview process. Following is the link:
http://www.geeksforgeeks.org/submatrix-sum-queries/
If anyone has any idea of is this ques, please explain to me.
The explanation on how to solve it is in great detail behind the link you provided.
public static int sumMatSumInConstantTime(int[][] mat, int is, int js, int ie, int je) {
processMatForConstantTimeSum(mat);
int sum = mat[ie][je];
int count = 0;
if (is - 1 >= 0) {
sum -= mat[is - 1][je];
count++;
}
if (js - 1 >= 0) {
sum -= mat[ie][js - 1];
count++;
}
/**
* since one rectangle is deducted twice
*/
if (count == 2)
sum += mat[is - 1][js - 1];
return sum;
}
private static void processMatForConstantTimeSum(int[][] mat) {
int r = mat.length;
int c = mat[0].length;
/**
* sum rows
*/
for (int i = 0; i < r; i++) {
int sum = 0;
for (int j = 0; j < c; j++) {
sum += mat[i][j];
mat[i][j] = sum;
}
}
/**
* sum cols
*/
for (int i = 0; i < c; i++) {
int sum = 0;
for (int j = 0; j < r; j++) {
sum += mat[j][i];
mat[j][i] = sum;
}
}
}
I have this problem, I need to generate from a given permutation not all combinations, but just those obtained after permuting 2 positions and without repetition. It's called the region of the a given permutation, for example given 1234 I want to generate :
2134
3214
4231
1324
1432
1243
the size of the region of any given permutation is , n(n-1)/2 , in this case it's 6 combinations .
Now, I have this programme , he does a little too much then what I want, he generates all 24 possible combinations :
public class PossibleCombinations {
public static void main(String[] args) {
Scanner s=new Scanner(System.in);
System.out.println("Entrer a mumber");
int n=s.nextInt();
int[] currentab = new int[n];
// fill in the table 1 TO N
for (int i = 1; i <= n; i++) {
currentab[i - 1] = i;
}
int total = 0;
for (;;) {
total++;
boolean[] used = new boolean[n + 1];
Arrays.fill(used, true);
for (int i = 0; i < n; i++) {
System.out.print(currentab[i] + " ");
}
System.out.println();
used[currentab[n - 1]] = false;
int pos = -1;
for (int i = n - 2; i >= 0; i--) {
used[currentab[i]] = false;
if (currentab[i] < currentab[i + 1]) {
pos = i;
break;
}
}
if (pos == -1) {
break;
}
for (int i = currentab[pos] + 1; i <= n; i++) {
if (!used[i]) {
currentab[pos] = i;
used[i] = true;
break;
}
}
for (int i = 1; i <= n; i++) {
if (!used[i]) {
currentab[++pos] = i;
}
}
}
System.out.println(total);
}
}
the Question is how can I fix this programme to turn it into a programme that generates only the combinations wanted .
How about something simple like
public static void printSwapTwo(int n) {
int count = 0;
StringBuilder sb = new StringBuilder();
for(int i = 0; i < n - 1;i++)
for(int j = i + 1; j < n; j++) {
// gives all the pairs of i and j without repeats
sb.setLength(0);
for(int k = 1; k <= n; k++) sb.append(k);
char tmp = sb.charAt(i);
sb.setCharAt(i, sb.charAt(j));
sb.setCharAt(j, tmp);
System.out.println(sb);
count++;
}
System.out.println("total=" + count+" and should be " + n * (n - 1) / 2);
}