static string weird behavior Diamond Star Pattern problem - java

I'm trying to solve this problem given a number 5, we display:
*
*****
*********
*****
*
And so on. So you give it a number and it format it for you like above. I tried to solve it using this code bellow and I can't see where the problem is in my code.
public class Exe01 {
public static String space = "";//global space var
public static String ast = "";//global * var
public static String adjustAst(int numOfAst) {
Exe01.ast = "";
for (int i = numOfAst; i > 0; i--) {
Exe01.ast+="*";
}
return Exe01.ast;
}
public static String adjustSpaces(int numOfSpaces) {
Exe01.space = "";
for (int i = numOfSpaces; i > 0; i--) {
Exe01.space = Exe01.space + " ";
}
return Exe01.space;
}
public static void showAst(int num) {
if (num <= 0 || num % 2 == 0)
System.out.println("arg to the function need to be positive and odd");
else if (num == 1)
System.out.println("*");
else {
int mid = (int) (num / 2);
int numberOfSpaces = num - 1;
for (int i = 0; i < num; i++) {
int k = 0;
if (i < mid) {
k = k * 2 + 1;
System.out.println(Exe01.adjustSpaces(numberOfSpaces) + Exe01.adjustAst(k));
numberOfSpaces = numberOfSpaces - 2;
} else if (i == mid) {
numberOfSpaces = 0;
k = k * 2 + 1;
System.out.println(Exe01.adjustSpaces(numberOfSpaces) + Exe01.adjustAst(k));
numberOfSpaces = numberOfSpaces + 2;
} else {
k = k - 4;
System.out.println(Exe01.adjustSpaces(numberOfSpaces) + Exe01.adjustAst(k));
numberOfSpaces = numberOfSpaces + 2;
}
}
}
}
public static void main(String args[]) {
Exe01.showAst(5);
}
}
At compilation time it gives me this:
*
*
*

Related

Display whole calculation for getting a factorial of a number (java)

I have a simple java program calculating the factorial of a number.
Output I get after running the program:
the factorial of 5 is 120
However I would like to generate output looking like this:
5 * 4 * 3 * 2 * 1 = 120
public static int calculateFactorial(int numInput) {
int factorial = 1;
for (int i = 1; i <= numInput; i++) {
factorial = factorial *i;
}
return factorial;
}
public static String calculateFactorialStr(int val) {
String res = IntStream.range(0, val)
.map(i -> val - i)
.mapToObj(String::valueOf)
.collect(Collectors.joining(" * "));
return res + " = " + calculateFactorial(val);
}
public static long calculateFactorial(int val) {
long res = 1;
for (int i = 2; i <= val; i++)
res *= i;
return res;
}
Static way:
Create your string in you function (this does not operate with n < 0) :
public static String calculateFactorial(int numInput) {
StringBuilder res = new StringBuilder();
int factorial = 1;
for (int i = 1; i <= numInput; i++) {
res.append(String.valueOf(i));
if (i != numInput) {
res.append(" * ");
}
factorial = factorial *i;
}
res.append(" = ").append(factorial);
return res.toString();
}
Object oriented way:
You can also create a Factorial class if you know about object oriented in Java (this does not operate with n < 0) :
import java.util.ArrayList;
import java.util.List;
public class Factorial {
private int number;
private int result;
public Factorial(int numInput) {
number = numInput;
int factorial = 1;
for (int i = 1; i <= numInput; i++) {
factorial = factorial * i;
}
result = factorial;
}
#Override
public String toString() {
StringBuilder res = new StringBuilder();
for (int i = 0; i <= number; i++) {
res.append(i);
if (i != number) {
res.append(" * ");
}
}
res.append(" = " + result);
return res.toString();
}
}
Then you can use a System.out.println(new Factorial(n)); to print the result
public static String calculateFactorial(int numInput) {
int factorial = 1;
String calc = "";
for (int i = 1; i <= numInput; i++) {
if (i != 1) {
calc += " * ";
}
calc += i;
factorial = factorial * i;
}
calc += " = " + factorial;
return calc;
}
or, if you prefer x * (x-1) * ... * 1
public static String calculateFactorial(int numInput) {
int factorial = 1;
String calc = "";
for (int i = numInput; i > 0; i--) {
if (i != numInput) {
calc += " * ";
}
calc += i;
factorial = factorial * i;
}
calc += " = " + factorial;
return calc;
}

Find the maximum product of two non overlapping palindromic subsequences

I am trying to find the maximum product of two non overlapping palindromic sub-sequences of string s that we'll refer to as a and b. I came up with below code but it's not giving correct output:
public static int max(String s) {
int[][] dp = new int[s.length()][s.length()];
for (int i = s.length() - 1; i >= 0; i--) {
dp[i][i] = 1;
for (int j = i+1; j < s.length(); j++) {
if (s.charAt(i) == s.charAt(j)) {
dp[i][j] = dp[i+1][j-1] + 2;
} else {
dp[i][j] = Math.max(dp[i+1][j], dp[i][j-1]);
}
}
}
return dp[0][s.length()-1];
}
For input string "acdapmpomp", we can choose a = "aca" and b ="pmpmp" to get a maximal product of score 3 * 5 = 15. But my program gives output as 5.
Firstly you should traverse the dp table to find out the length of longest palindromic subsequences using bottom up approach, then you can calculate the max product by multiplying dp[i][j] with dp[j+1][n-1] : Given below is the code in C++;
int longestPalindromicSubsequenceProduct(string x){
int n = x.size();
vector<vector<int>> dp(n,vector<int>(n,0));
for(int i=0;i<n;i++){
dp[i][i] = 1;
}
for(int k=1;k<n;k++){
for(int i=0;i<n-k;i++){
int j = i + k;
if(x[i]==x[j]){
dp[i][j] = 2 + dp[i+1][j-1];
} else{
dp[i][j] = max(dp[i][j-1],dp[i+1][j]);
}
}
}
int maxProd = 0;
for(int i=0;i<n;i++){
for(int j=0;j<n-1;j++){
maxProd = max(maxProd,dp[i][j]*dp[j+1][n-1]);
}
}
return maxProd;
}
int multiplyPalindrome(string s) {
int n=s.size(),m=0;
vector<vector<int>> dp(n, vector<int> (n));
for(int i=0;i<n;i++) dp[i][i]=1;
for (int cl=2; cl<=n; cl++) {
for (int i=0; i<n-cl+1; i++){
int j = i+cl-1;
if (s[i] == s[j] && cl == 2) dp[i][j] = 2;
else if (s[i] == s[j]) dp[i][j] = dp[i+1][j-1] + 2;
else dp[i][j] = max(dp[i][j-1], dp[i+1][j]);
}
}
for(int i=0;i<n-1;i++){
m = max( m, dp[0][i]*dp[i+1][n-1] );
}
return m;
}
int palSize(string &s, int mask) {
int p1 = 0, p2 = s.size(), res = 0;
while (p1 <= p2) {
if ((mask & (1 << p1)) == 0)
++p1;
else if ((mask & (1 << p2)) == 0)
--p2;
else if (s[p1] != s[p2])
return 0;
else
res += 1 + (p1++ != p2--);
}
return res;
}
int maxProduct(string s) {
int mask[4096] = {}, res = 0;
for (int m = 1; m < (1 << s.size()); ++m)
mask[m] = palSize(s, m);
for (int m1 = 1; m1 < (1 << s.size()); ++m1)
if (mask[m1])
for (int m2 = 1; m2 < (1 << s.size()); ++m2)
if ((m1 & m2) == 0)
res = max(res, mask[m1] * mask[m2]);
return res;
}
You can loop through all non-overlapping palindromic subsequences and return the maximum value.
public int longestPalindromicSubsequenceProduct(String str) {
int maxProduct = 0;
for (int k = 0; k < str.length(); k++) {
String left = str.substring(0, k);
String right = str.substring(k);
int currProduct = longestPalindromicSubsequence(left) * longestPalindromicSubsequence(right);
maxProduct = Math.max(maxProduct, currProduct);
}
return maxProduct;
}
private int longestPalindromicSubsequence(String org) {
String rev = new StringBuilder(org).reverse().toString();
return longestCommonSubsequence(org, rev);
}
private int longestCommonSubsequence(String str1, String str2) {
int rows = str1.length();
int cols = str2.length();
int[][] dp = new int[rows + 1][cols + 1];
for (int r = 1; r <= rows; r++) {
for (int c = 1; c <= cols; c++) {
if (str1.charAt(r - 1) == str2.charAt(c - 1)) dp[r][c] = 1 + dp[r - 1][c - 1];
else dp[r][c] = Math.max(dp[r - 1][c], dp[r][c - 1]);
}
}
return dp[rows][cols];
}
Your algorithm returns the maximum length of a palyndrome, not the maximum of the product of two lengths.
UPDATE
Here's a possible solution:
public static int max(String s) {
int max = 0;
for (int i = 1; i < s.length()-1; ++i) {
String p1 = bestPalyndrome(s, 0, i);
String p2 = bestPalyndrome(s, i, s.length());
int prod = p1.length()*p2.length();
if (prod > max) {
System.out.println(p1 + " " + p2 + " -> " + prod);
max = prod;
}
}
return max;
}
private static String bestPalyndrome(String s, int start, int end) {
if (start >= end) {
return "";
} else if (end-start == 1) {
return s.substring(start, end);
} else if (s.charAt(start) == s.charAt(end-1)) {
return s.charAt(start) + bestPalyndrome(s, start+1, end-1)
+ s.charAt(end-1);
} else {
String s1 = bestPalyndrome(s, start, end-1);
String s2 = bestPalyndrome(s, start+1, end);
return s2.length() > s1.length() ? s2 : s1;
}
}

ADAGAME4 Spoj Wrong Answer

Below is a Archive PROBLEM from SPOJ. Sample testCase is passing, but I am getting W/A on submission. I am missing some testCase(testCases). Need help to figure out what case I am missing and/or what I am doing wrong here.
Ada the Ladybug is playing Game of Divisors against her friend Velvet Mite Vinit. The game has following rules. There is a pile of N stones between them. The player who's on move can pick at least 1 an at most σ(N) stones (where σ(N) stands for number of divisors of N). Obviously, N changes after each move. The one who won't get any stones (N == 0) loses.
As Ada the Ladybug is a lady, so she moves first. Can you decide who will be the winner? Assume that both players play optimally.
Input
The first line of input will contain 1 ≤ T ≤ 10^5, the number of test-cases.
The next T lines will contain 1 ≤ N ≤ 2*10^7, the number of stones which are initially in pile.
Output
Output the name of winner, so either "Ada" or "Vinit".
Sample Input:
8
1
3
5
6
11
1000001
1000000
29
Sample Output:
Ada
Vinit
Ada
Ada
Vinit
Vinit
Ada
Ada
CODE
import java.io.*;
public class Main
{
public static int max_size = 2 * (int)Math.pow(10,7) + 1;
//public static int max_size = 25;
//public static int max_size = 2 * (int)Math.pow(10,6) + 1;
public static boolean[] dp = new boolean[max_size];
public static int[] lastPrimeDivisor = new int[max_size];
public static int[] numOfDivisors = new int[max_size];
public static void main(String[] args) throws IOException
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
preprocess();
int t = Integer.parseInt(br.readLine());
while(t > 0)
{
int n = Integer.parseInt(br.readLine());
if(dp[n] == true)
System.out.println("Ada");
else
System.out.println("Vinit");
t--;
}
}
public static void markLastPrimeDivisor()
{
for(int i = 0 ; i < max_size ; i++)
{
lastPrimeDivisor[i] = 1;
}
for(int i = 2 ; i < max_size ; i += 2)
{
lastPrimeDivisor[i] = 2;
}
int o = (int)Math.sqrt(max_size);
for(int i = 3 ; i < max_size; i++)
{
if(lastPrimeDivisor[i] != 1)
{
continue;
}
lastPrimeDivisor[i] = i;
if(i <= o)
{
for(int j = i * i ; j < max_size ; j += 2 * i)
{
lastPrimeDivisor[j] = i;
}
}
}
/*for(int i = 1 ; i < max_size ; i++)
System.out.println("last prime of " + i + " is " + lastPrimeDivisor[i]);*/
}
public static void countDivisors(int num)
{
int original = num;
int result = 1;
int currDivisorCount = 1;
int currDivisor = lastPrimeDivisor[num];
int nextDivisor;
while(currDivisor != 1)
{
num = num / currDivisor;
nextDivisor = lastPrimeDivisor[num];
if(nextDivisor == currDivisor)
{
currDivisorCount++;
}
else
{
result = result * (currDivisorCount + 1);
currDivisorCount = 1;
currDivisor = nextDivisor;
}
}
if(num != 1)
{
result = result * (currDivisorCount + 1);
}
//System.out.println("result for num : " + original + ", " + result);
numOfDivisors[original] = result;
}
public static void countAllDivisors()
{
markLastPrimeDivisor();
for(int i = 2 ; i < max_size ; i++)
{
countDivisors(i);
//System.out.println("num of divisors of " + i + " = " + numOfDivisors[i]);
}
}
public static void preprocess()
{
countAllDivisors();
dp[0] = dp[1] = dp[2] = true;
for(int i = 3 ; i < max_size ; i++)
{
int flag = 0;
int limit = numOfDivisors[i];
//If for any i - j, we get false,for playing optimally
//the current opponent will choose to take j stones out of the
//pile as for i - j stones, the other player is not winning.
for(int j = 1 ; j <= limit; j++)
{
if(dp[i - j] == false)
{
dp[i] = true;
flag = 1;
break;
}
}
if(flag == 0)
dp[i] = false;
}
}
}
There is a subtle bug in your countDivisors() function. It assumes
that lastPrimeDivisor[num] – as the name indicates – returns the
largest prime factor of the given argument.
However, that is not the case. For example, lastPrimeDivisor[num] = 2
for all even numbers, or lastPrimeDivisor[7 * 89] = 7.
The reason is that in
public static void markLastPrimeDivisor()
{
// ...
for(int i = 3 ; i < max_size; i++)
{
// ...
if(i <= o)
{
for(int j = i * i ; j < max_size ; j += 2 * i)
{
lastPrimeDivisor[j] = i;
}
}
}
}
only array elements starting at i * i are updated.
So lastPrimeDivisor[num] is in fact some prime divisor of num, but not
necessarily the largest. As a consequence, numOfDivisors[55447] is computed
as 8 instead of the correct value 6.
Therefore in countDivisors(), the exponent of a prime factor in num
must be determined explicitly by repeated division.
Then you can use that the divisors function is multiplicative. This leads to
the following implementation:
public static void countAllDivisors() {
// Fill the `somePrimeDivisor` array:
computePrimeDivisors();
numOfDivisors[1] = 1;
for (int num = 2 ; num < max_size ; num++) {
int divisor = somePrimeDivisor[num];
if (divisor == num) {
// `num` is a prime
numOfDivisors[num] = 2;
} else {
int n = num / divisor;
int count = 1;
while (n % divisor == 0) {
count++;
n /= divisor;
}
// `divisor^count` contributes to `count + 1` in the number of divisors,
// now use multiplicative property:
numOfDivisors[num] = (count + 1) * numOfDivisors[n];
}
}
}

Why doesn't my program run correctly?

for my school project I have to create a program that outputs perfect numbers based on how many perfect numbers the user(teacher) want. The user can pick any number from 1-4 and it should display however many number the user chooses. Here is my current code. Please ignore the sumupTo, factorial, isprime, and the testGoldbach methods, please only look at the Perfect numbers method/code.
import java.util.Scanner;
public class MyMathB
{
public static int sumUpTo(int n)
{
int sum = 0;
for (int k = 1; k <= n; k++)
sum += k;
return sum;
}
public static long factorial(int n)
{
long f = 1;
for (int k = 2; k <= n; k++)
f *= k;
return f;
}
public static boolean isPrime(int n)
{
if (n <= 1)
return false;
int m = 2;
while (m * m <= n)
{
if (n % m == 0)
return false;
m++;
}
return true;
}
public static void PerfectNumbers(int number)
{
System.out.println("How many perfect numbers would you like to see? Please enter an integer from 1 to 4");
Scanner s = new Scanner(System.in);
int numbersToSee = s.nextInt();
int counts = 0;
for(counts = 0; counts <= numbersToSee; counts++)
{
for (int n = 5; n <= 10000; n++)
{
int temp = 0;
for(int i = 1; i <= number / 2; i++)
{
if (number % i == 0)
{
temp += i;
}
if (temp == number)
{
System.out.println(number);
}
}
}
}
}
public static boolean testGoldbach(int bigNum)
{
for (int n = 6; n <= bigNum; n += 2)
{
boolean found2primes = false;
for (int p = 3; p <= n/2; p += 2)
{
if (isPrime(p) && isPrime(n - p))
found2primes = true;
}
if (!found2primes)
{
System.out.println(n + " is not a sum of two primes!");
return false;
}
}
return true;
}
public static void main(String[] args)
{
Scanner kb = new Scanner(System.in);
int n;
do
{
System.out.print("Enter an integer from 4 to 20: ");
n = kb.nextInt();
} while (n < 4 || n > 20);
kb.close();
System.out.println();
System.out.println("1 + ... + " + n + " = " + sumUpTo(n));
System.out.println(n + "! = " + factorial(n));
System.out.println("Primes: ");
for (int k = 1; k <= n; k++)
if (isPrime(k))
System.out.print(k + " ");
System.out.println();
System.out.println("Goldbach conjecture up to " + n + ": " + testGoldbach(n));
}
}
you didn't declare the variable "number" in your method.
Edit: you didn't SET the variable number to anything, I misworded my last statement.

Genetic Evolution of Strings in Java

Ultimately, I am trying to create a genetic algorithm that will evolve a string that matches a target string. I do not have a conventional coding background, so my code will be extremely messy. Here is my complete code.
public class Main {
public static double similarity(String s1, String s2) {
String longer = s1, shorter = s2;
if (s1.length() < s2.length()) { // longer should always have greater
// length
longer = s2;
shorter = s1;
}
int longerLength = longer.length();
if (longerLength == 0) {
return 1.0;
/* both strings are zero length */ }
/*
* // If you have StringUtils, you can use it to calculate the edit
* distance: return (longerLength -
* StringUtils.getLevenshteinDistance(longer, shorter)) / (double)
* longerLength;
*/
return (longerLength - editDistance(longer, shorter)) / (double) longerLength;
}
public static int editDistance(String s1, String s2) {
s1 = s1.toLowerCase();
s2 = s2.toLowerCase();
int[] costs = new int[s2.length() + 1];
for (int i = 0; i <= s1.length(); i++) {
int lastValue = i;
for (int j = 0; j <= s2.length(); j++) {
if (i == 0)
costs[j] = j;
else {
if (j > 0) {
int newValue = costs[j - 1];
if (s1.charAt(i - 1) != s2.charAt(j - 1))
newValue = Math.min(Math.min(newValue, lastValue), costs[j]) + 1;
costs[j - 1] = lastValue;
lastValue = newValue;
}
}
}
if (i > 0)
costs[s2.length()] = lastValue;
}
return costs[s2.length()];
}
public static void printSimilarity(String s, String t) {
System.out.println(String.format("%.3f is the similarity between \"%s\" and \"%s\"", similarity(s, t), s, t));
}
private static String getCharForNumber(int i) {
char[] alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ ".toCharArray();
if (i > 27) {
return null;
}
return Character.toString(alphabet[i]);
}
public static String generateString(int numChar) {
Random random = new Random();
String randomString = "";
for (int i = 0; i < numChar; i++) {
String temp = getCharForNumber(random.nextInt(27));
randomString += temp;
}
return randomString;
}
public static String returnTwoChildren(String s1, String s2, boolean first) {
// chromosomes
// String s1;
// String s2;
// crossovers
String c1;
String c2;
Random r = new Random();
// get a random indices
int ind1 = r.nextInt(s1.length());
// make sure ind2 > ind1... leaving this part out;
// break both strings into parts like in your picture
String s1part1 = s1.substring(0, ind1);
String s1part2 = s1.substring(ind1);
String s2part1 = s2.substring(0, ind1);
String s2part2 = s2.substring(ind1);
// combine the parts
c1 = s1part1 + s2part2;
c2 = s2part1 + s1part2;
if (first)
return c1;
return c2;
}
Random random;
static String[] population;
static String[] childPopulation;
static String target = "Cat";
public static void createPopulation(int size) {
population = new String[size];
for (int i = 0; i < size; i++) {
population[i] = generateString(3);
// System.out.println(population[i]);
// if (similarity(population[i], target) > 0.3)
// printSimilarity(population[i], target);
}
}
public static void fitness(boolean print) {
for (int i = 0; i < population.length; i++) {
for (int j = i + 1; j < population.length; j++) {
if (similarity(population[j], target) > similarity(population[i], target)) {
String temp = population[i];
population[i] = population[j];
population[j] = temp;
}
}
if (print && similarity(population[i], target) > 0)
System.out.println(population[i] + ", " + similarity(population[i], target));
}
}
public static void createChildPopulation(int size) {
childPopulation = new String[size];
for (int i = 0; i < population.length; i += 2) {
population[i] = returnTwoChildren(population[i], population[i + 1], true);
population[i + 1] = returnTwoChildren(population[i], population[i + 1], false);
}
}
public static void mutate() {
Random random = new Random();
int prob;
String sub1, sub2;
for (int i = 0; i < population.length; i++) {
for (int j = 1; j < population[i].length(); j++) {
prob = random.nextInt(100);
if (prob == 0) {
sub1 = population[i].substring(0, j);
sub2 = population[i].substring(j);
population[i] = sub1 + generateString(1) + sub2;
}
}
}
}
public Main() {
// fightGame(random);
//String string1 = "acbdefghijklmnop";
//String string2 = "1234567891234567";
int populationSize = 80;
createPopulation(populationSize);
boolean print = true;
for (int i = 0; i <= 800; i++) {
if (i % 5 == 0) {
print = true;
System.out.println("Generation: " + i);
}
fitness(print);
if (similarity(population[0], target) == 1.0) {
System.out.println("Succeded! Generation: " + i + " String: " + population[0]);
break;
}
createChildPopulation(populationSize);
mutate();
print = false;
}
// returnTwoChildren(string1, string2);
System.out.println("Done!");
}
public static void main(String[] args) {
new Main();
}
}
When I run the program, it is fine for a few generations then seems to find a problem. I don't know why the strings are getting longer (than three characters). If someone could help point me to the problem, and solution, I would be extremely grateful.
Problematic is this part:
public static void mutate() {
Random random = new Random();
int prob;
String sub1, sub2;
for (int i = 0; i < population.length; i++) {
for (int j = 1; j < population[i].length(); j++) {
prob = random.nextInt(100);
if (prob == 0) {
sub1 = population[i].substring(0, j);
sub2 = population[i].substring(j);
population[i] = sub1 + generateString(1) + sub2;
}
}
}
}
When you hit prob = 0 then your population[i] is mutating, but instead of changing one letter you add one letter.
I think it shold be:
sub1 = population[i].substring(0, j-1);
instead of
sub1 = population[i].substring(0, j);
Then your strings will have always 3 letters

Categories

Resources