Algorithm in array works for i=1 only - java

Hello fellow eingineers/programmers. I'm calculating the course of the moment from right to left of a cantilever arm. problem: the algorithm works for a=0, a=1 and then it doesn't work. Code below:
objekte[] is an array of objects of two classes- Einzelmoment (moment) and Punktlast (single force).
for (int a = 0; a < verlauf[0].length; a++) {
for (int k = 0; k < objekte.length; k++) {
if (a == 0) {
verlauf[0][0] = objekte[k].getLage();
verlauf[1][a] = objekte[k].getKraft();
if (objekte[k].getClass() == Punktlast.class) {
verlauf[2][a] = -(objekte[k].getKraft() * (objekte[a]
.getLage() - objekte[k].getLage()));
} else if (objekte[k].getClass() == Einzelmoment.class) {
verlauf[2][a] = -(objekte[k].getMoment());
}
}
else {
verlauf[0][a] = objekte[k].getLage();
verlauf[1][a] = objekte[k].getKraft() + verlauf[1][a - 1];
if (objekte[k].getClass() == Punktlast.class) {
for (int j = 1; j == k; j++) {
if (objekte[k - j].getClass() == Einzelmoment.class) {
verlauf[2][a] += -(objekte[k - j].getMoment());
} else if (objekte[k - j].getClass() == Punktlast.class) {
verlauf[2][a] += -(objekte[k - j].getKraft() * (objekte[k- j].getLage() - objekte[k].getLage()));
}
j++;
}
}
else if (objekte[k].getClass() == Einzelmoment.class) {
for (int j = 1; j == k; j++) {
if (objekte[k - j].getClass() == Einzelmoment.class) {
verlauf[2][a] += -(objekte[k - j].getMoment() + objekte[k].getMoment());
} else if (objekte[k - j].getClass() == Punktlast.class) {
verlauf[2][a] += -(objekte[k - j].getKraft() * (objekte[k- j].getLage() - objekte[k].getLage()));
}
j++;
}
}
}
a++;
}
}
Hope somehow this makes sense. As you can see here, it works for a=1 but it doesn't continue to the rest of the objects. Where's the problem in the code that it stops by a=1? Thank you in advance!

Related

Converted this code from C# to Java, is there anything else that can be simplified in Java?

This is a function that, given an array A consisting of N integers, where A[K] denotes the height of the K-th tree, returns the number of ways of cutting out one tree, so that the remaining trees are aesthetically pleasing. If it is not possible to achieve the desired result, the function should return -1. If it's already aesthetically pleasing without any removal, the function should return 0.
This is the code written in C#.
using System;
namespace activity_problem
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("");
}
}
class Solution
{
public int solution(int[] a)
{
if (isAesthetic(a))
{
return 0;
}
int aestheticPatternCount = 0;
for (int j = 0; j < a.Length; j++)
{
int[] newA = copyArrayWithoutAnElement(a, j);
if (isAesthetic(newA))
{
aestheticPatternCount++;
}
}
if (aestheticPatternCount == 0)
{
return -1;
}
else
{
return aestheticPatternCount;
}
}
private int[] copyArrayWithoutAnElement(int[] array, int indexOfElementToBeRemoved)
{
int arrayLength = array.Length;
int[] newArr = new int[arrayLength - 1];
int tempK = 0;
for (int k = 0; k < arrayLength; k++)
{
if (k != indexOfElementToBeRemoved)
{
newArr[tempK++] = array[k];
}
}
return newArr;
}
private Boolean isAesthetic(int[] array)
{
int newArrayLength = array.Length;
int increasingFlag = 0;
for (int i = 0; i < newArrayLength; i++)
{
if (increasingFlag == 0)
{
if (array[i] < array[i + 1])
{
increasingFlag = 1;
}
else
{
increasingFlag = 2;
}
}
else
{
if (increasingFlag == 1)
{
if (i % 2 == 1 && array[i] > array[i - 1])
{
}
else if (i % 2 == 0 && array[i] < array[i - 1])
{
}
else
{
return false;
}
}
else
{
if (i % 2 == 1 && array[i] < array[i - 1])
{
}
else if (i % 2 == 0 && array[i] > array[i - 1])
{
}
else
{
return false;
}
}
}
}
return true;
}
}
}
Converted into JAVA, is there anything else that could be possibly simplified?
public class Main {
public static void main(String[] args) {
Solution sol = new Solution();
int solution = sol.solution(new int[]{1, 2, 3, 4, 5});
System.out.println(solution);
}
public static class Solution {
public int solution(int[] a){
if (isAesthetic(a))
{
return 0;
}
int aestheticPatternCount = 0;
for (int j = 0; j < a.length; j++)
{
int[] newA = copyArrayWithoutAnElement(a, j);
if (isAesthetic(newA))
{
aestheticPatternCount++;
}
}
if (aestheticPatternCount == 0)
{
return -1;
}
else
{
return aestheticPatternCount;
}
}
private int[] copyArrayWithoutAnElement(int[] array, int indexOfElementToBeRemoved)
{
int arrayLength = array.length;
int[] newArr = new int[arrayLength - 1];
int tempK = 0;
for (int k = 0; k < arrayLength; k++)
{
if (k != indexOfElementToBeRemoved)
{
newArr[tempK++] = array[k];
}
}
return newArr;
}
private Boolean isAesthetic(int[] array)
{
int newArrayLength = array.length;
int increasingFlag = 0;
for (int i = 0; i < newArrayLength; i++)
{
if (increasingFlag == 0)
{
if (array[i] < array[i + 1])
{
increasingFlag = 1;
}
else
{
increasingFlag = 2;
}
}
else
{
if (increasingFlag == 1)
{
if (i % 2 == 1 && array[i] > array[i - 1])
{
}
else if (i % 2 == 0 && array[i] < array[i - 1])
{
}
else
{
return false;
}
}
else
{
if (i % 2 == 1 && array[i] < array[i - 1])
{
}
else if (i % 2 == 0 && array[i] > array[i - 1])
{
}
else
{
return false;
}
}
}
}
return true;
}
}
}
I'm currently trying to learn algorithm in Java so any help or input is really appreciated.
For readability:
One thing you can do to simplify the code is remove the empty else-if branches.
Another would be to follow the usual java conventions and have the curly braces on the same line, for example:
if (something) {
// ...
} else if (somethingElse) {
// ...
} else {
// ...
}
For the actual program logic:
Instead of looking to port the code exactly as it is written, you can simplify some parts of it by using the Collections api. For example, if you need an array (and not some kind of List) then you can do all the work with removing elements, etc with a collection (e.g. ArrayList) and convert it to an array at the end.
Also, as noted in the comments there is a lot of comparison going on. If you can simplify that and do less comparing you'll have a better algorithm.
I would suggest starting with some unit tests with cases to validate against both the old code and new code.

How do I combine an Output of two for loops into a "table" format?

I used two for loops to convert miles to km and km to miles respectively for selected values. However the issue I am facing is that the output for the first for loop is not side by side with the output of the second table. Appreciate some help on this!
public static double miletoKilometer(double mile) {
double conversion = mile * 1.609;
return conversion;
}
public static double kilometerToMile(double km) {
double conversion2 = km / 1.609;
return conversion2;
}
public static void main(String[] args) {
int mileInput = 0;
double kmOutput = 0;
int kmInput = 0;
double mileOutput = 0;
int displayRow1 = 0;
int displayRow2 = 0;
System.out.print("Miles\tKilometres\tKilometres\tMiles \n");
for (int i = 0; i < 11; i++) {
if (i == 1 || i == 2 || i == 9 || i == 10) {
mileInput = i;
System.out.printf("\n" + i);
kmOutput = miletoKilometer(mileInput);
System.out.printf("\t %.3f\n", kmOutput);
}
}
for (int j = 0; j < 66; j++) {
if (j == 20 || j == 25 || j == 60 || j == 65) {
kmInput = j;
System.out.printf("\n\t\t " + j);
mileOutput = kilometerToMile(kmInput);
System.out.printf("\t\t%.3f", mileOutput);
}
}
}
Current Output:
enter image description here
Changing your loop to match the code below should put everything in the right order. Not the most elegant solution but it gets the job done.
int j = 0;
for (int i = 0; i < 11; i++) {
if (i == 1 || i == 2 || i == 9 || i == 10) {
mileInput = i;
System.out.printf("\n" + i);
kmOutput = miletoKilometer(mileInput);
System.out.printf("\t %.3f", kmOutput);
for (; j < 66; j++) {
if (j == 20 || j == 25 || j == 60 || j == 65) {
kmInput = j;
System.out.printf("\t\t " + j);
mileOutput = kilometerToMile(kmInput);
System.out.printf("\t\t%.3f\n", mileOutput);
j++;
break;
}
}
}
}

How would I get my printToScreenNew() method to print my new generation? The result I am getting is my package name followed by Generation#33909752

public Generation newGen() {
Generation newGen = new Generation();
for (int i = 1; i < 26; i++) {
for (int j = 1; j < 76; j++) {
int x = i;
int y = j;
int n = numberOfNeighbors(x, y);
if (gen[i][j] == 'X') {
if (n == 2 || n == 3) {
newGen.gen[i][j] = 'X';
}
if (n != 2 || n != 3) {
newGen.gen[i][j] = '.';
}
}
if (gen[i][j] == '.') {
if (n == 3) {
newGen.gen[i][j] = 'X';
}
if (n != 3) {
newGen.gen[i][j] = '.';
}
}
}
}
return newGen;
}
//I'm taking a char[][] called gen and passing it to the above method, and it is supposed to return a value of type Generation(the class) and then print it to the console in the method below.
public void printToScreenNew() {
Generation newGen = newGen();
System.out.print(newGen.toString());
System.out.println("\n");
}

Game Of Life loop error

So I'm currently working on a program based on Conway's Game of Life, and this certain method requires me to update the 2d array to define which cells are alive. I've run my JUnit tests, but when the test for the method runs, it says it's infinitely looping. Any ideas why?
public void update() {
boolean temp ;
for (int i = 0; i < numberOfRows(); i++) {
for (int j = 0; j < numberOfColumns(); j++) {
temp = false;
if (cellAt(i, j)) {
temp = true;
}
if (temp=true) {
if (neighborCount(i, j) < 2 || neighborCount(i, j) > 3) {
society[i][j] = false;
}
} else {
if (neighborCount(i, j) == 3) {
society[i][j] = true;
}
}
}
}
}
Here is the other methods that are used in this one
cellAt():
public boolean cellAt(int row, int col) {
if (society[row][col] == true) {
return true;
} else {
return false;
}
}
neighborCount():
public int neighborCount(int row, int col) {
int counter = 0;
for (int i = ((row + numberOfRows() - 1) % numberOfRows()); i == ((row + 1) % numberOfRows())
|| i == row
|| i == (((row + numberOfRows() - 1)) % numberOfRows())
|| i == numberOfRows(); i++) {
i = i % numberOfRows();
for (int j = (((col + numberOfColumns() - 1)) % numberOfColumns()); j == ((col + 1) % numberOfColumns())
|| j == col
|| j == (((col + numberOfColumns() - 1)) % numberOfColumns())
|| j == numberOfColumns(); j++) {
j = j % numberOfColumns();
if (society[i][j] == true) {
counter++;
}
}
}
return counter;
}
You need to use comparison(==) instead of assignment(=) here:
if (temp=true) {
which will always return true
Change it to
if (temp == true) {
or simply use "Jean-François Savard" suggestion
if(temp)
Figured it out. neighborCount() was just horribly written and the for loops were repeating.

Cannot read repeating characters

I'm writing a code to read a string and count sets of repeating
public int countRepeatedCharacters()
{
int c = 0;
for (int i = 1; i < word.length() - 1; i++)
{
if (word.charAt(i) == word.charAt(i + 1)) // found a repetition
{
if ( word.charAt(i - 1) != word.charAt(i)) {
c++;
}
}
}
return c;
}
If I try the input
aabbcdaaaabb
I should have 4 sets of repeat decimals
aa | bb | aaaa | bb
and I know I'm not reading the first set aa because my index starts at 1. I tried fixing it around to read zero but then I tr to fix the entire loop to work with the change and I failed, is there any advice as to how to change my index or loop?
Try this code:
public int countRepeatedCharacters(String word)
{
int c = 0;
Character last = null;
bool counted = false;
for (int i = 0; i < word.length(); i++)
{
if (last != null && last.equals(word.charAt(i))) { // same as previous characted
if (!counted) { // if not counted this character yet, count it
c++;
counted = true;
}
}
else { // new char, so update last and reset counted to false
last = word.charAt(i);
counted = false
}
}
return c;
}
Edit - counted aaaa as 4, fixed to count as 1
from what I understood from your question, you want to count number of repeating sets, then this should help.
for (int i = 0; i < word.length()-1; i++){
if (word.charAt(i) == word.charAt(i + 1)){ // found a repetition
if (i==0 || word.charAt(i - 1) != word.charAt(i)) {
c++;
}
}
}
Try this----
public int countRepeatedCharacters()
{
int c = 0,x=0;
boolean charMatched=false;
for (int i = 0; i < word.length(); i++)
{
if(i==word.length()-1)
{
if (word.charAt(i-1) == word.charAt(i))
c++;
break;
}
if (word.charAt(i) == word.charAt(i + 1)) // found a repetition
{
charMatched=true;
continue;
}
if(charMatched==true)
c++;
charMatched=false;
}
return c;
}
Try this method. It counts the sets of repeating charactors.
public static void main(String[] args) {
String word = "aabbcdaaaabbc";
int c = 0;
for (int i = 0; i < word.length()-1; i++) {
// found a repetition
if (word.charAt(i) == word.charAt(i + 1)) {
int k = 0;
while((i + k + 1) < word.length()) {
if(word.charAt(i+k) == word.charAt(i + k + 1)) {
k++;
continue;
}
else {
break;
}
}
c++;
i+=k-1;
}
}
System.out.println(c);
}
You can try something like this:-
public static void main(String str[]) {
String word = "aabbcdaaaabbc";
int c = 1;
for (int i = 0; i < word.length() - 1; i++) {
if (word.charAt(i) == word.charAt(i + 1)) {
c++;
} else {
System.out.println(word.charAt(i)+ " = " +c);
c = 1;
}
}
System.out.println(word.charAt(word.length()-1)+ " = " +c);
}
You can modify this as per your needs, by removing the sysouts and other stuffs.
Using length() -1 is causing you to not consider the last character in your calculations.
This is causing you to lose the last repetitive character.
Finally, I would have done this as follows:
public static int countRepeatedCharacters(String word)
{
boolean withinRepeating = false;
int c = 0;
for (int i = 1; i < word.length(); i++)
{
if (!withinRepeating && (withinRepeating = word.charAt(i) == word.charAt(i - 1)))
c++;
else
withinRepeating = word.charAt(i) == word.charAt(i - 1);
}
return c;
}

Categories

Resources