I have an programming assignment in Java.
I have implemented it by making an nCr ( http://en.wikipedia.org/wiki/Combination ) function then using a double for loop to make the triangle by printing it out.
However, the assignment calls for a uneven 2d array to be created and then populated by adding the two numbers from the previous lines and then printing the array out.
I know I am going to have to do the assignment the way it asks, however I have a small feeling that (at least for small triangles anyway) that the approach I have implemented is better.
Which is the better approach?
I'd think the method called for by the assignment would be better. You're method requires a number of multiplications to calculate each of the elements of the triangle. This number will increase for each row of the triangle you need to calculate.
The assignment's method, however, requires a single addition for each element of the triangle.
If I understand your question, you are trying to compare two approaches to generating Pascal's triangle:
By running an nCr function to populate each cell of the triangle.
By generating the triangle in one pass by filling in each cell by a simple addition.
The second approach seems hands-down better. Am I missing something? Even if you use memoization in your nCr function there is overhead in those calls.
By using recursion
/*By using recursion*/
class RecursivePascal {
public static void main(String args[]) {
int n = 100;
for (int i = 0; i < n; i++) {
for (int j = 0; j <= i; j++) {
//System.out.print(i+","+j+" ");
System.out.print(pascal(i, j) + " ");
}
System.out.println();
}
}
static int pascal(int i, int j) {
if (j == 0)
return 1;
else if (j == i)
return 1;
else {
return pascal(i - 1, j - 1) + pascal(i - 1, j);
}
}
}
By using simple logic
/*By using logic*/
class p {
public static void main(String args[]) {
int one[] = {1};
int n = 13;
System.out.println("1");
for (int j = 0; j < n; j++) {
int two[] = new int[one.length + 1];
int twoCounter = 0;
for (int i = 0; i < one.length; i++) {
if (i == 0) {
two[twoCounter++] = one[i];
System.out.print(one[i] + " ");
}
if (i != 0) {
two[twoCounter++] = one[i] + one[i - 1];
System.out.print((one[i] + one[i - 1]) + " ");
}
if (i == one.length - 1) {
two[twoCounter++] = one[i];
System.out.print(one[i] + " ");
}
}
System.out.println();
one = two;
}
}
}
Related
I am creating a program that will take a wordlist of 5 000 strings and find the shortest path from one string to another. For example abc -> bac could print "abc, bbc, bac".
I am pretty sure about what I want to do, the only thing I'm not completely sure about is what datastructure should represent my wordlist. The goal is for the search(BFS) to run as fast as possible, so to sacrifice some space is no problem. I am thinking either a BST or an adjacency list, but since I'm no expert at datastrutcutres' timecomplexity I want to be certain before I start adjusting my code. Can anyone recommend one of the structures over the other? Or have I perhaps missed a datastructure that is an obvious alternative for this?
Looks like what you are looking for is the Levenshtein distance, here is the Rosetta code implementation, you should be able to change it to suit your need:
public class Levenshtein {
public static int distance(String a, String b) {
a = a.toLowerCase();
b = b.toLowerCase();
// i == 0
int [] costs = new int [b.length() + 1];
for (int j = 0; j < costs.length; j++)
costs[j] = j;
for (int i = 1; i <= a.length(); i++) {
// j == 0; nw = lev(i - 1, j)
costs[0] = i;
int nw = i - 1;
for (int j = 1; j <= b.length(); j++) {
int cj = Math.min(1 + Math.min(costs[j], costs[j - 1]), a.charAt(i - 1) == b.charAt(j - 1) ? nw : nw + 1);
nw = costs[j];
costs[j] = cj;
}
}
return costs[b.length()];
}
public static void main(String [] args) {
String [] data = { "kitten", "sitting", "saturday", "sunday", "rosettacode", "raisethysword" };
for (int i = 0; i < data.length; i += 2)
System.out.println("distance(" + data[i] + ", " + data[i+1] + ") = " + distance(data[i], data[i+1]));
}
}
So I just had a lesson on loops and nested loops. My professor said that nested loops can help us do tasks such as knowing if we rolled 2 different matching pairs with 4 dices (4242) I'm a bit confused on how that would work.
So I started to work it out and this is what I was able to create.
public boolean 4matchDice(String dice){
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
}
}
I used boolean as the return as it will tell us whether or not we have 2 different matching pairs.
Thing is, what do I put in the the loops? That's what's confusing me the most.
Here's a solution I came up with, seems to be returning the correct outcome for all the test cases I ran.
public static boolean matchDice(String dice) {
char[] diceArray = dice.toCharArray();
int pairs = 0;
for (int i = 0; i < 4; i++) {
for (int j = i + 1; j < dice.length(); j++) {
if (diceArray[i] == diceArray[j]) {
diceArray[i] = 'X';
diceArray[j] = 'Y';
pairs++;
}
}
}
return (pairs > 1);
}
If you're only comparing two sets with two dice each, this is enough:
public boolean match4Dice(int first, int second, int third, int fourth) {
if ((first == third && second == fourth) || (first == fourth && second == third)) {
return true;
}
return false;
}
But if you're comparing 2 sets with any number of dice, the following algorithm would suit you better.
public boolean matchDice(String firstDiceSet, String secondDiceSet) {
// validate input, string must contain numbers from 1 - 6 only.
// lenghts of strings firstDiceSet & secondDiceSet must be equal
// works for any number of dice in each set.
// The dice only match if all numbers in the firstDiceSet all present in the secondDiceSet also.
// Let us count the matching numbers to check if this true.
int numberOfMatches = 0;
for (int i = 0; i < firstDiceSet.length(); i++) {
for (int j = 0; j < secondDiceSet.length(); j++) {
if (firstDiceSet[i] == secondDiceSet[j]) { // and not used
// increment number of matches
// mark secondDiceSet[j] as used, so that you do not count the same match twice.
// account for cases where firstDiceSet = "33" and the secondDiceSet = "35"
}
}
}
// your dice set match if the following condition is true
return (numberOfMatches == secondDiceSet.length());
}
Hi I just coded up a solution that will take "4242" as an input, although sindhu_sp's method is more practical i believe. I just wanted to show you another example to help your learning of java!
public static boolean fourMatchDice(String dice){
int match = 0;
for (int i = 0; i < dice.length(); i++){
for (int j = i+1; j < dice.length(); j++){
if (dice.toCharArray()[i] == dice.toCharArray()[j]){
System.out.println("does " + dice.toCharArray()[i] + " = " + dice.toCharArray()[j]);
match ++;
}
}
}
if(match == 2) *EDIT* //Change to (match >= 2) if 4 of the same pair is allowed.
return true;
return false;
}
public static void main(String[] args) {
System.out.println(fourMatchDice("4242"));
}
output:
does 4 = 4
does 2 = 2
true
I know this question is old, and I solved the calculation part of it. but my problem is in the main method and I could not find a solution for it.
I need to call the Pascal triangle function recursively, but also have the ability to print it upside-down too. I can print the first 10 rows, but I don't know how to flip it to be upside down. here is my code:
public class RecursivePascalTriangle {
static int get_pascal(int row, int col) {
if (col == 0 || col == row) {
return 1;
} else {
return get_pascal(row - 1, col - 1) + get_pascal(row - 1, col);
}
}
public static void main(String[] args) {
for (int i = 0; i < 10; i++) {
for (int k = 0; k <= i; k++) {
System.out.print(get_pascal(i, k) + " ");
}
System.out.println();
}
}
}
Can anyone help me in this? I am stuck here. I don't want to use any for loops.Thank you!
Hey guys. I've been strugling with a backtraking problem for hours. Can anyone lend me a hand? Here is the problem:
n camels numbered from 1 to n are the arranged order. I want to rearrange so that each camel has a diferent camel in front.
This is what I have so far:
import java.util.*;
public class NCamile{
static int size;
static int count;
static char[] arrN= new char[100];
public static void main(String[] args){
System.out.print("Enter word: ");
String numar = getInt();
size = numar.length();
count=0;
for(int i=0; i < size ; i++){
arrN[i] = numar.charAt(i);
}
backtraking(size);
}
public static void backtraking(int newsize){
if (newsize == 1){
return;
}
for(int i=0 ; i < newsize; i++){
backtraking(newsize - 1);
if(newsize == 2 ){
display();
}
rotate(newsize);
}
}
public static void rotate(int newsize){
int position = size - newsize;
for(int i = position + 1; i < newsize; i++){
char gigi;
gigi = arrN[i - 1];
arrN[i - 1] = arrN [i];
arrN[i] = gigi;
}
}
public static void display(){
if (count < 9){
System.out.print(" ");
}
System.out.print(++count+ ")" + " ");
for(int i = 0 ; i < size ; i++)
System.out.print(arrN[i]);
System.out.print(" ");
if(count % 10 == 0){
System.out.println(" ");
}
}
public static String getInt(){
Scanner scan = new Scanner(System.in);
String s = scan.next();
return s;
}
}
With this, the algorithems show me every posible solution to rearrange a string, but it dosen't respect the last condition of the problem. I've tried ading this:
for(int j = 0 ; j < size ; j++){
if (array[j] !=[array[j + 1] )
display()
}
But after I added it I got about 10 times more displayed words then it should have shown me
Can anyone give me an idea on what should I do?
If you're only asked to insure that
i) a single new arrangement is produced, and
ii)that new arrangement must satisfy the condition that each camel follows a camel different from the one it followed in the original arrangement,
then you can easily satisfy this just by reversing the list of camels.
Surely this is not optimized solution, but for simply gettin result I would consider checking all of the permutations. Method producing every permutation wouldn't be hard to write (see e.g. String permutation) and checking if some camel has the same backtraced won't be any effort at all.
--- edit
So... Few things mended, few not:
I worked on String, not char array. Char array is completely misunderstand in this problem. It's better to use String object (cause in fact, String is char array) or int array (this have been hard to me, cause I haven't found any permutation method to be applied with such parameter). So the main method looks now:
private static String word;
public static void main(String[] args)
{
System.out.print("Enter word: ");
Scanner scan = new Scanner(System.in);
word = scan.next();
permutation(word);
}
I deleted your class variables (length, count, etc...) cause they are unnecessary right now. Writing out String is quite simple and if you would like to change output format - use String.length property instead.
Permutation method is copied from mentioned source, and little modified. It looks following:
public static void permutation(String s)
{
permutation("", s);
}
private static void permutation(String prefix, String s)
{
int n = s.length();
if (n == 0)
{
if (camelFit(prefix))
System.out.println(prefix);
}
else
{
for (int i = 0; i < n; i++)
permutation(prefix + s.charAt(i),
s.substring(0, i) + s.substring(i + 1, n));
}
}
if you would uncomment line checking if (camelFit (prefix)) it would display every permutation of input String. But! We would like to print only these camel chains, which fits problem conditions. How do we check if given chain is so? Simple method:
private static boolean camelFit(String prefix)
{
for (int i = 0; i < word.length() - 1; i++)
{
char camel = word.charAt(i);
char camelFollow = word.charAt(i+1);
for (int j = 0; j < prefix.length() - 1; j++)
{
if (prefix.charAt(j)==camel && prefix.charAt(j+1)==camelFollow)
{
return false;
}
}
}
return true;
}
Maybe not so simple, because we have to check every pair of input chain (every follower and followed) with every pair of output chain. If there isn't any match between any two pairs - given chain is fine.
Please notice, that this solution is absolutely non-optimized. Finding permutations is O(n!) complexity and checking pairs is O(n^2) complexity. Final complexity is O(n^2)*O(n!) so very, very high.
in the inner for loop I have 0<p1,p2,p3<3 and they are integer. I want this for loop to assign value from 0 till 3 to each parameter in demoMethod.i.e., once the for loop executes it will send parameter like (1,2,3) to demomethod and for the second time it will send parameter (2,3,0) to the demoMethod. also the order of these three numbers are not important and they must be different .it means that after two times that for loop executes it doesn't send parameter like (1,2,3) and (2,3,1). thanks
public void Points(List<Point> pointList) {
int n = pointList.size();
if (n <= 2) {
System.out.println("null");
} else if (n == 3) {
drawingLine();
} else {
for(int i = 0;i<n;i++){
for(int j = 1;j<=(n-1)*(n-2)*(n-3)/6;j++){
demoMethod(p1,p2,p3);
}
}
}
}
I am not entirely sure what you are trying to do, but if I understand you correctly, you want to do something like this (?):
for(int i = 0;i<n;i++){
for(int j = 1;j<=(n-1)*(n-2)*(n-3)/6;j++){
int p1 = j % 4;
int p2 = (j + 1) % 4;
int p3 = (j + 2) % 4;
demoMethod(p1,p2,p3);
}
}