public long process(long[][] theArray) {
long result = 0l;
int xDimension = 0;
int yDimension = 0;
for (int i = 0; i < theArray.length; i++) {
for (int j = 0; j < theArray[0].length; j++) {
if (((yDimension + 12) < theArray.length) && ((xDimension + 12) < theArray[0].length)) {
result = (theArray[yDimension][xDimension + 1]) + (theArray[yDimension][xDimension + 2])
+ (theArray[yDimension + 1][xDimension]) + (theArray[yDimension + 1][xDimension + 3])
+ (theArray[yDimension + 2][xDimension]) + (theArray[yDimension + 2][xDimension + 3])
+ (theArray[yDimension + 3][xDimension + 1]) + (theArray[yDimension + 3][xDimension + 2]);
}
xDimension++;
}
xDimension -= (theArray[0].length);
yDimension++;
}
return result;
}// method()
--> my console says : Index 5 out of bounds for length 5. But how is that possible together with my if-condition?
xDimension starts with 0 and will be negative after one iteration of the outer loop.
Related
I'm trying to reach this :
1 + (1 + 2) + (1 + 2 + 3) + ... + (1 + 2 + 3 + ... + n)
I'm already getting this result:-
(1 + 2) + (2 + 3)
with this code :
int n = 8;
for (int i = 1; i < n; i++){
int j = i + 1;
System.out.print("(" + i + " + " + j + ")");
}
How can I achieve the top result ?
You need two loops like this :
int n = 8;
String del;
String del2 = "";
for (int i = 1; i <= n; i++) {
System.out.print(del2 + "(");
del = "";
for (int j = 1; j <= i; j++) {
System.out.print(del + j);
del = " + ";
}
System.out.print(")");
del2 = " + ";
}
code demo
Move the declaration of j before the loop and initialize it with 0, then just add the current i to j.
That would solve what? – AKSW
This would calculate the sum of the equation.
To print the equation you also need one loop only:
int n = 8;
StringBuilder equation = new StringBuilder("1");
StringBuilder equationGroup = new StringBuilder("1");
for (int i = 2; i < n; i++) {
equationGroup.append(" + ");
equationGroup.append(i);
equation.append(" + (");
equation.append(equationGroup.toString());
equation.append(")");
}
System.out.println(equation.toString());
Well, thanks #YCF_L for your answer it's the correct one, but this complete one after edit, i posted it in case some one need the complete solution:
int n = 8;
String del;
String delPlus = "";
String rightPract = "", leftPract = "";
for (int i = 2; i < n; i++) {
System.out.print(delPlus + rightPract);
del = "";
for (int j = 1; j < i; j++) {
System.out.print(del + j);
del = " + ";
}
System.out.print(leftPract);
delPlus = " + ";
rightPract = "(";
leftPract = ")";
}
Now the result is :-
1 + (1 + 2) + (1 + 2 + 3) + (1 + 2 + 3 + 4) + (1 + 2 + 3 + 4 + 5) + (1 + 2 + 3 + 4 + 5 + 6)
If you take the recursion approach you have to think of it as a recursion inside another recursion. add(i,n) generates 1 and (1+2) and (1+2+3) up to (1+2+3...n). then the sum(i,n) recursively sum them together
public static int add(int i, int n){
if(i == n){
return n;
}
return i + add(i+1,n);
}
public static int sum(int i, int n){
if(i == n){
return add(0,n);
}
return add(0, i) + sum(i+1,n);
}
public static void main(String[] args){
int n = 8;
System.out.print(sum(0, n));
}
I know my code can be made simpler and more efficient but I am trying to get it to work this way.
I want to get the biggest number consisting of 5 digits from the string. I would like to use the subString method. As output, I just get the first 5 numbers, and it doesn't loop through the rest of the string.
public class thousandDigits
{
public static void main(String[] args)
{
String num = new String ("73167176531330624919225119674426574742355349194934" +
"96983520312774506326239578318016984801869478851843" +
"85861560789112949495459501737958331952853208805511" +
"12540698747158523863050715693290963295227443043557" +
"66896648950445244523161731856403098711121722383113" +
"62229893423380308135336276614282806444486645238749" +
"30358907296290491560440772390713810515859307960866" +
"70172427121883998797908792274921901699720888093776" +
"65727333001053367881220235421809751254540594752243" +
"52584907711670556013604839586446706324415722155397" +
"53697817977846174064955149290862569321978468622482" +
"83972241375657056057490261407972968652414535100474" +
"82166370484403199890008895243450658541227588666881" +
"16427171479924442928230863465674813919123162824586" +
"17866458359124566529476545682848912883142607690042" +
"24219022671055626321111109370544217506941658960408" +
"07198403850962455444362981230987879927244284909188" +
"84580156166097919133875499200524063689912560717606" +
"05886116467109405077541002256983155200055935729725" +
"71636269561882670428252483600823257530420752963450") ;
int greatest = 0;
int max = -1;
int numChar = Integer.parseInt(num.substring(0, 5));
for (int i = 0; i < num.length() - 5; i++)
{
greatest = numChar;
if (max < greatest)
{
max = greatest;
}
}
System.out.print(max);
}
}
The output is 7316 but it should be 99890 as the biggest 5 digit number that comes up.
That's because you do not update the numChar inside the loop. You only do it once at the beginning. Also, the calculated substring needs to go from i to i+5 in the loop.
int greatest = 0;
int max = -1;
//int numChar = Integer.parseInt(num.substring(0, 5)); <-- Not Here
for (int i = 0; i < num.length() - 5; i++) {
int numChar = Integer.parseInt(num.substring(i, i + 5)); // <-- but here
greatest = numChar;
if (max < greatest) {
max = greatest;
}
}
You don't need to parseInt the value as String comparison is fine.
You can do
String num = "73167176531330624919225119674426574742355349194934" +
"96983520312774506326239578318016984801869478851843" +
"85861560789112949495459501737958331952853208805511" +
"12540698747158523863050715693290963295227443043557" +
"66896648950445244523161731856403098711121722383113" +
"62229893423380308135336276614282806444486645238749" +
"30358907296290491560440772390713810515859307960866" +
"70172427121883998797908792274921901699720888093776" +
"65727333001053367881220235421809751254540594752243" +
"52584907711670556013604839586446706324415722155397" +
"53697817977846174064955149290862569321978468622482" +
"83972241375657056057490261407972968652414535100474" +
"82166370484403199890008895243450658541227588666881" +
"16427171479924442928230863465674813919123162824586" +
"17866458359124566529476545682848912883142607690042" +
"24219022671055626321111109370544217506941658960408" +
"07198403850962455444362981230987879927244284909188" +
"84580156166097919133875499200524063689912560717606" +
"05886116467109405077541002256983155200055935729725" +
"71636269561882670428252483600823257530420752963450";
String largest = IntStream.range(0, num.length() - 5)
.mapToObj(i -> num.substring(i, i + 5))
.max(Comparator.<String>naturalOrder())
.orElseThrow(AssertionError::new);
System.out.println(largest);
prints
99890
The code below gets the failed indexes from a text file and prints it to a webpage and the lower loop does same but for the passes. I want to calculate the percentages and I have tried the code below but it returns 0.0%.
Please help as I am a novice programmer.
int i = 0;
while ((i = (secondLine.indexOf(failures, i) + 1)) > 0) {
System.out.println(i);
feedbackString += "<strong style='color: red;'><li>Failed: </strong><strong>" + i + "</strong> - " + "out of " + resultString.length() + " tests.<br>";
}
int j = 0;
while ((j = (secondLine.indexOf(passed, j) + 1)) > 0) {
System.out.println(j);
feedbackString += "<strong style='color: green;'><li>Passed: </strong><strong>" + j + "</strong> - Well done.</li>";
}
totalScore = j * 100 / resultString.length();
System.out.println(totalScore);
feedbackString += "Your submission scored " + totalScore + "%.<br>";
You want to make your division a floating point division :
totalScore = (double)j * 100 / resultString.length();
That's assuming totalScore is a double.
Otherwise, j * 100 / resultString.length() would use int division, so if resultString.length() > 100, the result would be 0.
As Tom mentioned, the condition of the while loop :
while ((j = (secondLine.indexOf(passed, j) + 1)) > 0)
ensures the it will end only once j <= 0. Therefore, it's no wonder (double)j * 100 / resultString.length() is 0.
If you want to count the number of passes you need a second counter :
int j = 0;
int passes = 0;
while ((j = (secondLine.indexOf(passed, j) + 1)) > 0) {
passes++;
System.out.println(j);
feedbackString += "<strong style='color: green;'><li>Passed: </strong><strong>" + j + "</strong> - Well done.</li>";
}
Then
totalScore = (double)passes * 100 / resultString.length();
The problem is that j is not the count of failures, it's an index to the failure. Since you indexOf returns -1 in case it didn't find the element and you use it to mark the end of search, it will always be -1. Add 1 and you always get j == 0.
You can do it that way:
String secondLine = "pfpffpfffp";
char failures = 'f';
char passed = 'p';
ArrayList<Integer> failuresList = new ArrayList<Integer>();
ArrayList<Integer> passedList = new ArrayList<Integer>();
String feedbackString = "";
for (int i = 0; i < secondLine.length(); i++) {
char o = secondLine.charAt(i);
if (o == failures) {
failuresList.add(i);
} else {
passedList.add(i);
}
}
int countFailures = failuresList.size();
int countPassed = passedList.size();
int countTotal = countFailures + countPassed;
for (int i = 0; i < failuresList.size(); i++) {
System.out.println(failuresList.get(i));
feedbackString += "<strong style='color: red;'><li>Failed: </strong><strong>" + i + "</strong> - " + "out of " + countTotal + " tests.<br>";
}
for (int i = 0; i < passedList.size(); i++) {
System.out.println(passedList.get(i));
feedbackString += "<strong style='color: green;'><li>Passed: </strong><strong>" + i + "</strong> - Well done.</li>";
}
double totalScore = countPassed * 100.0 / countTotal;
System.out.println(totalScore);
feedbackString += "Your submission scored " + totalScore + "%.<br>";
System.out.println(feedbackString);
I'm very new to Java and maybe my question is a bit irritating.
I have two for loops in my code and I want to go to the beginning of each one by a for-else statement.
public static void main(String[] args)
{
int[][] x=new int[1000][1000];
int[] Z=new int[1000];
lable1:
for(int i=1; i<=1000; i++)
{
Z[i]=rand1.nextInt(1000);
System.out.println("Z["+i +"] = " + Z[i] );
if(Z[i]>0 && Z[i]<=Nk)
{
int Z1=Z[i]-1;
lable2:
for(int j = 1; j<=Z1;j++ )
{
x[i][j]= rand2.nextInt(1000);
sum+=x[i][j];
if( sum<1000)
{
x[i][(j+1)]=1000-sum;
System.out.println("x[" + i+"][" + j + "] = " + x[i][j]);
System.out.println("Nx[" + i+"][" + (j+1) + "] = " +x[i][(j+1)]);
}
else{
// ????
//Goto lable2;
}
}
}
else{
//goto label1;
// ????
}
}
}
You can break to any defined label (within scope) by using:
break label;
Same holds for continue.
Here is something to read.
In your particular example, removing the elses would do what you want.
Just use continue keyword.. It will continue with the next iteration.. No need to label your loop.. As you are not continuing the outer loop from the inner one.. Or, if you want to continue with outer loop, you can use continue with a label...
And you should use your for loop from j = 0 to j < z1..
for(int j = 0; j < Z1;j++ ) {
if( sum<1000) {
x[i][(j+1)]=1000-sum;
System.out.println("x[" + i+"][" + j + "] = " + x[i][j]);
System.out.println("Nx[" + i+"][" + (j+1) + "] = " +x[i][(j+1)]);
}
else{ // Not needed if your else does not contain anything else..
continue;
}
}
In fact you don't need an else block at all.. If you are not doing any further processing in it..
Just remove it.. It will automatically go to your loop..
Suggestion: - You should use coding convention.. variable names start with lowercase letter or underscore.. (Z1 -> z1)
Here you are:
public static void main(String[] args) {
int[][] x = new int[1000][1000];
int[] Z = new int[1000];
boolean resetOuterCycle = true;
for (int i = 0; i < 1000; i++) {
Z[i] = rand1.nextInt(1000);
System.out.println("Z[" + i + "] = " + Z[i]);
if (Z[i] > 0 && Z[i] <= Nk) {
int Z1 = Z[i] - 1;
boolean resetInnerCycle = true;
for (int j = 0; j < Z1; j++) {
x[i][j] = rand2.nextInt(1000);
sum += x[i][j];
if (sum < 1000) {
x[i][(j + 1)] = 1000 - sum;
System.out.println("x[" + i + "][" + j + "] = " + x[i][j]);
System.out.println("Nx[" + i + "][" + (j + 1) + "] = " + x[i][(j + 1)]);
} else if (resetInnerCycle) {
j = 0;
resetInnerCycle = false;
}
}
} else if (resetOuterCycle) {
i = 0;
resetOuterCycle = false;
}
}
}
- In your above code you can use 2 approach to do it...
1st Approach : No else part
for (int i = 0; i < 1000; i++) {
if (Z[i] > 0 && Z[i] <= Nk){
for (int j = 0; j < Z1; j++) {
if(sum < 1000){
}
}
}
}
2nd Approach : With else part and continue
for (int i = 0; i < 1000; i++) {
if (Z[i] > 0 && Z[i] <= Nk){
for (int j = 0; j < Z1; j++) {
if(sum < 1000){
}else{
continue;
}
}
}else{
continue;
}
}
public class ProjectEulerProb2 {
int firstInt = 1, secondInt = 2, thirdInt = 0, answer = 0;
int[] array = new int[4000000];
int[] evenArray = new int[90];
public static void main(String args[]) {
ProjectEulerProb2 prob = new ProjectEulerProb2();
prob.doIt();
prob = null;
}
public void doIt() {
for (int i = 0; i <= 4000000; i++) {
if (i == 0) {
thirdInt = firstInt + secondInt;
}
else {
firstInt = secondInt;
secondInt = thirdInt;
thirdInt = firstInt + secondInt;
}
array[i] = firstInt;
array[i + 1] = secondInt;
array[i + 2] = thirdInt;
if (thirdInt >= 4000000) {
break;
}
}
for (int j = 0; j <= 90; j = j + 3) {
if (j == 0) {
if (array[j + 1] % 2 == 0) {
System.out.println(" " + array[j + 1] % 2 + " " + array[j + 1]);
evenArray[j / 3] = array[j + 1];
}
if (array[j + 2] % 2 == 0) {
System.out.println(" " + array[j + 2] % 2 + " " + array[j + 2]);
evenArray[j / 3] = array[j + 2];
}
}
if (array[j] % 2 == 0) {
System.out.println(" " + array[j] % 2 + " " + array[j]);
evenArray[j / 3] = array[j];
}
}
for (int u = 0; u < evenArray.length; u++) {
if (u == 0) {
answer = evenArray[u];
}
else {
answer = answer + evenArray[u];
}
}
System.out.println(answer);
}
}
Could someone please help me find the problem? Every time I print the values of the array it comes out as 0 instead of the assigned value.
EDIT: Okay I took all the 'System.out.println's'
out that I didn't need.
EDIT 2: Okay so I rewrote the code to not use arrays anymore. Still interested in figuring out where I went wrong with the last version though.
public class ProjectEulerProb2Other {
static int firstInt=1, secondInt=2, thirdInt=0, answer=0;
public static void main(String[] args){
for(int i = 0; i<=4000000;i++){
if(i==0){
if(firstInt%2==0){
answer = answer+firstInt;
}
if(secondInt%2==0){
answer = answer+secondInt;
}
thirdInt = firstInt+secondInt;
}else{
firstInt = secondInt;
secondInt = thirdInt;
thirdInt = firstInt+secondInt;
if(thirdInt%2==0){
answer = answer+thirdInt;
}
}
if(thirdInt>=4000000){
System.out.println(answer);
break;
}
}
}
}
There is no problem with how you add elements to your array.
array[i] = firstInt;
Is correct. However, there are problems in your logic. Since this is probably an homework, I'll let you find them :)
EDIT
Okay so the problem was in this loop in your first version:
for (int j = 0; j <= 90; j = j + 3) {
if (j == 0) { //Bad idea!!
if (array[j + 1] % 2 == 0) { //Always false. array[0 + 1] == 1
System.out.println(" " + array[j + 1] % 2 + " " + array[j + 1]);
evenArray[j / 3] = array[j + 1];
}
if (array[j + 2] % 2 == 0) { //Always true. array[0 + 2] == 2
System.out.println(" " + array[j + 2] % 2 + " " + array[j + 2]);
evenArray[j / 3] = array[j + 2];
}
}
if (array[j] % 2 == 0) {
System.out.println(" " + array[j] % 2 + " " + array[j]);
evenArray[j / 3] = array[j];
}
}
My fix:
int jCpt = 0; //To add in evenArray in an orderly manner
for (int j = 0; jCpt < 90 && j < 4000000; ++j) { //Changed this
if (array[j] % 2 == 0) {
System.out.println(" " + array[j] % 2 + " " + array[j]);
evenArray[jCpt++] = array[j]; //We add alement #j from array to evenArray
/* Equivalent of
* evenArray[jCpt] = array[j];
* jCpt = jCpt + 1;
*/
}
}
But that version is probably better:
int evenCpt = 0; //To insert the even numbers one after the other
int fibonacciCpt = 0; //To iterate through the fibonacci numbers in array
for (; evenCpt < 90 && fibonacciCpt < 4000000; ++fibonacciCpt) {
if (array[fibonacciCpt] % 2 == 0)
evenArray[evenCpt++] = array[fibonacciCpt];
}
Congratulations, you solved Problem #2 :)