3D multidimensional array output not matching initialization data - java

I've been working on a code segment that flattens a 3D dimensional array, however I've encountered a rather baffling situation with the following code.
The array used is initialized as follows:
int array[][][] = {
{
{000, 001, 002},
{010, 011, 012},
{020, 021, 022},
},
{
{100, 101, 102},
{110, 111, 112},
{120, 121, 122},
},
{
{200, 201, 202},
{210, 211, 212},
{220, 221, 222},
}
};
And then outputting the array through a basic nested for loop.
The output is formatted through a custom DecimalFormat that allows me to print the floating 0's.
DecimalFormat xFormat = new DecimalFormat("000");
for(int z = 0; z < array[0].length; z++) {
for(int y = 0; y < array[1].length; y++) {
for(int x = 0; x < array[2].length; x++) {
System.out.println("I = "+ i + " Element at i = " + xFormat.format(array[z][y][x]));
}
}
}
This loop is used immediately after the initialization of the array, yet the output is what completely baffles me
I = 0 Element at i = 000
I = 1 Element at i = 001
I = 2 Element at i = 002
I = 3 Element at i = 008 <------- =/= 010
I = 4 Element at i = 009 <------- =/= 011
I = 5 Element at i = 010 <------- =/= 012
I = 6 Element at i = 016 <------- =/= 020
I = 7 Element at i = 017 <------- =/= 021
I = 8 Element at i = 018 <------- =/= 022
I = 9 Element at i = 100
I = 10 Element at i = 101
I = 11 Element at i = 102
I = 12 Element at i = 110
I = 13 Element at i = 111
I = 14 Element at i = 112
I = 15 Element at i = 120
I = 16 Element at i = 121
I = 17 Element at i = 122
I = 18 Element at i = 200
I = 19 Element at i = 201
I = 20 Element at i = 202
I = 21 Element at i = 210
I = 22 Element at i = 211
I = 23 Element at i = 212
I = 24 Element at i = 220
I = 25 Element at i = 221
I = 26 Element at i = 222
This seems rather elementary to me, yet I'm not sure what I'm missing at this point. The majority of the loop prints out right, yet it's this part in the middle that's not outputting correctly, and searches on multidimensional array issues haven't yielded much in the way of solutions

Its because 0* (0 prefix) is used to store octal numbers (base8)
{000, 001, 002}, //0,1,2
{010, 011, 012}, //8,9,10
{020, 021, 022}, //16,17,18
That swhy 010 translates to 8 decimal, 11 to 9 etc etc. Just like 0x*is used to store hexadecimals, aod ***b to store binaries. DecimalFormat gets value of octal 010, that equals to 9, and this is what you are getting in the output.
Rest of the values are decimals, because they do not start with 0. You can prefix every other walue with 0 and see what will happen.

Related

Finding all valid iterations ranges that produce constants in multiple locations

I need an algorithm to produce valid iteration ranges for p^l with constants in multiple places.
I have it working but it is very inefficient. I believe there is math that can solve this but I am not sure what it is. Currently I have to find each valid set of iteration ranges for each constant I want. Then I must overlap all the ranges to find iterations where all constants are present.
This is the code for doing so:
public ArrayList<Range> findRangesForSingleSearch(int searchPos, int value) {
ArrayList<Range> iterationRanges = new ArrayList<Range>();
BigInteger p = new BigInteger(""+possibilities);
BigInteger interationMax = p.pow(length-1);
BigInteger pMinus1 = new BigInteger(""+(possibilities - 1));
BigInteger totalIterationsBeforeTarget = p.pow(searchPos);
BigInteger skipIterations =
totalIterationsBeforeTarget.multiply(pMinus1).add(BigInteger.ONE);
totalIterationsBeforeTarget = totalIterationsBeforeTarget.subtract(BigInteger.ONE);
int[] startData = new int[length];
for(int i = 0; i < length; i++) {
if(i==searchPos) {
startData[i] = value;
}else {
startData[i]=0;
}
}
BigInteger startIteration = getPosition(startData);
BigInteger currentIteration = startIteration;
for(BigInteger i = new BigInteger(""+0); i.compareTo(interationMax.divide(totalIterationsBeforeTarget.add(BigInteger.ONE))) < 0;
i = i.add(BigInteger.ONE)) {
BigInteger lowerBound = currentIteration;
currentIteration = currentIteration.add(totalIterationsBeforeTarget);
BigInteger upperBound = currentIteration;
iterationRanges.add(new Range(lowerBound, upperBound));
currentIteration = currentIteration.add(skipIterations);
}
return iterationRanges;
}
This is the code for overlapping the ranges:
public ArrayList<Range> condenseRanges(ArrayList<Range> r1, ArrayList<Range> r2){
ArrayList<Range> newRanges = new ArrayList<Range>();
int ai = 0, bi = 0, alength = r1.size(), blength = r2.size();
BigInteger ax,ay,bx,by;
while(ai < alength && bi < blength) {
ax = r1.get(ai).getLowerBound();
ay = r1.get(ai).getUpperBound();
bx = r2.get(bi).getLowerBound();
by = r2.get(bi).getUpperBound();
if (ay.compareTo(bx) < 0) {
ai++;
} else if (by.compareTo(ax) < 0) {
bi++;
} else {
newRanges.add(condenseRange(r1.get(ai), r2.get(bi)));
if (ay.compareTo(by) < 0) {
ai++;
} else {
bi++;
}
}
}
return newRanges;
}
The meat of my question boils down to if there is a way to combine or tweak the following so that it generates the pre-combined ranges:
totalIterationsBeforeTarget
skipIterations
startIteration
Examples of ranges and iteration correlation + execution of code:
Possibilities:2
Length:8
Total Iterations Possible: 2^8 = 256
Search: position 1,2,3 must equal 1
Found Ranges:
14 -> 15
30 -> 31
46 -> 47
62 -> 63
78 -> 79
94 -> 95
110 -> 111
126 -> 127
142 -> 143
158 -> 159
174 -> 175
190 -> 191
206 -> 207
222 -> 223
238 -> 239
254 -> 255
Example Correlation:
Note the iteration/binary elements are indexed right to left
example: 3rd position, 2nd position, 1st position, zed position
The first range is 14 -> 15:
14 converted to binary is 1110 which matches the search of elements 1,2,3 having a
value of 1
15 converted to binary is 1111 which matches the search of elements 1,2,3 having a
value of 1
13 and 16 are omitted because their binary values are 1101,10000 which do not meet
the requirement of elements 1,2,3 having a value of 1
Then the algorithm jumps to the next valid range 30 -> 31:
30 converted to binary is 11110
31 converted to binary is 11111
If anything is unclear, ask and I can explain in further detail.

generate a Series / return nth term in the series

I need to generate a sequence such that its members contain only 1, 2, 3 digits. For example, 1 2 3 11 12 13 21 22 23 31 32 33 111 .... and so on up to 10^18th term.
I'm not able to deduce any pattern for this. It seems impossible to write a code up to 10^18 numbers of terms in the series.
1, 2, 3, 11, 12, 13, 21, 22, 23, 31, 32, 33, 111, 112, 113, 121, 122,
123, 131, 132, 133, 211, 212, 213, 221, 222, 223, 231, 232, 233, 311,
312, 313, 321, 322, 323, 331, 332, 333, 1111, 1112, 1113, 1121, 1122,
1123, 1131, 1132, 1133, 1211, 1212, 1213, 1221 ...
I expect to find the given n-th term in the series. It's a number system which contains only 1, 2, 3 or is combinations of these digits as a number as explained in the sequence just like our normal number system.
This is just a base-3 numbering system only the digits go from 1 to 3 instead of 0 to 2. The math works out the same way:
1 = 1*3^0
2 = 2*3^0
3 = 3*3^0
4 = 1*3^1 + 1*3^0
5 = 1*3^1 + 2*3^0
6 = 1*3^1 + 3*3^0
7 = 2*3^1 + 1*3^0
...
19 = 1*3^2 + 3*3^1 + 1*3^0
Write two methods:
digit(n): computes the right-most digit for a given n. Some test cases: digit(4) = 1, digit(5)=2, digit(15)=3.
leftover(n): computes the number which represents n but with the right-most digit chopped off. Some test cases: leftover(4) = 1, leftover(15) = 4, leftover(23) = 7.
Now combine the two methods into the solution to your problem which repeatedly chops off the right most digit until there's nothing left. You might find it easier to do this recursively.
The sequence you've mentioned already is known as Numbers that contain only 1's, 2's and 3's. It is formulated by Hieronymus Fischer.
a(n) = sum_{j=0..m-1} (1 + b(j) mod 3)*10^j,
where m = floor(log_3(2*n+1)), b(j) = floor((2*n+1-3^m)/(2*3^j)).
You can examine explanation of the formula on the aforementioned link above. I've written so far basic level of it using long. To reach 10^18th term, you need to use BigInteger class of Java.
class SequenceGeneratorWith123 {
// Written by Soner
private static double logOfBase(long base, long num) {
return Math.log(num) / Math.log(base);
}
private static int mfunc(long n) {
return (int) Math.floor(logOfBase(3, 2 * n + 1));
}
private static int b(int j, double m, long n) {
return (int) Math.floor((2 * n + 1 - Math.pow(3, m)) / (2 * Math.pow(3, j)));
}
public static void main(String[] args) {
for (int i = 0; i < 9; i++) {
long n = (long) Math.pow(10, i);
int m = mfunc(n);
long sum = 0;
for (int j = 0; j < m ; j++) {
sum += ((1 + b(j, m, n) % 3) * Math.pow(10, j));
}
System.out.printf("a(10^%d) = %d\n", i, sum);
}
System.out.println("After the point, overflow will occur " +
"because of long type.");
}
}
Output:
a(10^0) = 1
a(10^1) = 31
a(10^2) = 3131
a(10^3) = 323231
a(10^4) = 111123331
a(10^5) = 11231311131
a(10^6) = 1212133131231
a(10^7) = 123133223331331
a(10^8) = 13221311111312132
After the point, overflow will occur because of long type.
You just need to play with the code, that is, we can obtain your wish by merely changing main() somewhat.
long n = 1;
// How many terms you need you can alter it by pow() method.
// In this example 10^2 = 100 terms will be obtained.
int term = (int)Math.pow(10, 2);
for (int i = 0; i < term; i++) {
int m = mfunc(n);
long sum = 0;
for (int j = 0; j < m ; j++) {
sum += ((1 + b(j, m, n) % 3) * Math.pow(10, j));
}
System.out.printf("%d. term = %d\n", i + 1, sum);
n++;
}
Output:
1. term = 1
2. term = 2
3. term = 3
4. term = 11
5. term = 12
6. term = 13
7. term = 21
8. term = 22
9. term = 23
10. term = 31
11. term = 32
12. term = 33
13. term = 111
14. term = 112
15. term = 113
16. term = 121
17. term = 122
18. term = 123
19. term = 131
20. term = 132
21. term = 133
22. term = 211
23. term = 212
24. term = 213
25. term = 221
26. term = 222
27. term = 223
28. term = 231
29. term = 232
30. term = 233
31. term = 311
32. term = 312
33. term = 313
34. term = 321
35. term = 322
36. term = 323
37. term = 331
38. term = 332
39. term = 333
40. term = 1111
41. term = 1112
42. term = 1113
43. term = 1121
44. term = 1122
45. term = 1123
46. term = 1131
47. term = 1132
48. term = 1133
49. term = 1211
50. term = 1212
51. term = 1213
52. term = 1221
53. term = 1222
54. term = 1223
55. term = 1231
56. term = 1232
57. term = 1233
58. term = 1311
59. term = 1312
60. term = 1313
61. term = 1321
62. term = 1322
63. term = 1323
64. term = 1331
65. term = 1332
66. term = 1333
67. term = 2111
68. term = 2112
69. term = 2113
70. term = 2121
71. term = 2122
72. term = 2123
73. term = 2131
74. term = 2132
75. term = 2133
76. term = 2211
77. term = 2212
78. term = 2213
79. term = 2221
80. term = 2222
81. term = 2223
82. term = 2231
83. term = 2232
84. term = 2233
85. term = 2311
86. term = 2312
87. term = 2313
88. term = 2321
89. term = 2322
90. term = 2323
91. term = 2331
92. term = 2332
93. term = 2333
94. term = 3111
95. term = 3112
96. term = 3113
97. term = 3121
98. term = 3122
99. term = 3123
100. term = 3131

Algorithm to solve unfinished equations in Java

I am trying to write a program that when given unfinished equations will output the lowest digit that will work or -1 if none will work. I have all my input set up but at this stage I am not sure how to continue.
Example inputs are: 1+1=?, 123*45?=5?088, -5?*-1=5, 19--45=5?, ??*??=302?
Any tips on how to tackle this would be appreciated.
import java.util.Scanner;
import java.util.regex.*;
public class Runes {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int caseNo = sc.nextInt();
for (int c = 0; c < caseNo; c++) {
String input = sc.next();
String re1="([-]?[0-9?]+)"; // -int1 or int1
String re2="([+\\-*])"; //+ or - or *
String re3="([-]?[0-9?]+)"; // -int2 or int2
String re4="(=)"; // Equals
String re5="([-]?[0-9?]+)"; // -int3 or int3
Pattern pattern = Pattern.compile(re1+re2+re3+re4+re5,Pattern.CASE_INSENSITIVE | Pattern.DOTALL);
Matcher matcher = pattern.matcher(input);
if (matcher.find()) {
String int1 = matcher.group(1);
String op1 = matcher.group(2);
String int2 = matcher.group(3);
String op2 = matcher.group(4);
String int3 = matcher.group(5);
System.out.println(int1 + " " + op1 + " " + int2 + " " + op2 + " " + int3);
}
}
}
}
Here's one way to create your Java application.
Create an Integer index array with a value for each question mark. In other words, if there are 5 question marks, your Integer index array has 5 elements.
Loop through the Integer index array. In other words, for 5 question marks, the values ought to be (see layout below).
Looping through the Integer index array, substitute the index values for the question marks.
Check to see if the string is a valid equation. If so, save it in a List.
When the looping is finished, print the List values.
Here's the layout for point 2.
0, 0, 0, 0, 0
1, 0, 0, 0, 0
...
9, 0, 0, 0, 0
0, 1, 0, 0, 0
...
9, 9, 9, 9, 9
I used your input examples to create this output. I added spaces to the equations to make them easier to read. I manually formatted this output to fit on the screen
1 + 1 = ? --> 1 + 1 = 2
123 * 45? = 5?088 --> 123 * 456 = 56088
-5? * -1 = 5 --> No equation exists
19 - -45 = 5? --> No equation exists
?? * ?? = 302? --> 57 * 53 = 3021 53 * 57 = 3021 72 * 42 = 3024
42 * 72 = 3024 48 * 63 = 3024 56 * 54 = 3024
36 * 84 = 3024 84 * 36 = 3024 54 * 56 = 3024
63 * 48 = 3024 55 * 55 = 3025 89 * 34 = 3026
34 * 89 = 3026

longest common subsequence function does not work for all examples

EDIT: UP
The code does not work properly with the strings below.
"1 11 23 1 18 9 15 23 5"
"11 1 18 1 20 5 11 1"
EDIT: I noticed, that if I change 20 to 40 in second string, the function works properly...
For strings:
"12 4 55 11 8 43 22 90 5 88 15"
"15 66 4 36 43 22 78 88 32"
it works properly. Where is the problem?
Here is my code:
int[][] tabelka = new int[linia1.length()+1][linia2.length()+1];
for (int i = 0; i<linia1.length(); i++) {
for (j = 0; j<linia2.length(); j++) {
if ( linia1.charAt(i) == linia2.charAt(j) ) {
tabelka[i+1][j+1] = tabelka[i][j] + 1;
}
else {
tabelka[i+1][j+1] = Math.max(tabelka[i+1][j], tabelka[i][j+1]);
}
}
}
for (int i = 0; i<linia1.length(); i++) {
for (j = 0; j<linia2.length(); j++) {
System.out.println(tabelka[i][j]);
}
}
StringBuffer podciag = new StringBuffer();
for(int x = linia1.length(), y = linia2.length(); x != 0 && y != 0; ) {
if( tabelka[x][y] == tabelka[x-1][y] ) {
licznik++;
x--;
}
else if( tabelka[x][y] == tabelka[x][y-1] ) {
licznik++;
y--;
}
else {
licznik++;
assert linia1.charAt(x-1) == linia2.charAt(y-1);
podciag.append(linia1.charAt(x-1));
x--;
y--;
}
}
String buff = podciag.reverse().toString();
The output of this code (for the first two strings) is:
11 1 18 1 2 5
However, the output should be:
11 1 18 5
For a full / better explanation, please refer to:
http://www.geeksforgeeks.org/dynamic-programming-set-4-longest-common-subsequence/
http://www.geeksforgeeks.org/printing-longest-common-subsequence/
I think that you are constructing the array correctly. However, I am not sure about the way the table is being read in order to construct the LCS.
The idea is to start at the end of the 2D array solution[str1.length()][str2.length()] and if:
The last characters of str1 and str2 are equal then the last character is part of the LCS and decrement both indexes
If they are not equal, compare solution[i-1][j] and solution[i][j-1] and go in direction of greater value.
Repeat until either of the indexes are 0.

Subtract elements in an array

I have an array with this values 80 82 84 90 94 is it possible to subtract the values so the output could be 0 2 2 6 4?
I´ve edited the question:Now I want to use this in an android cursor adapter but I´m getting index out of bounds when it reaches the calculation of the difference.
public void bindView(View view, Context context, Cursor cursor) {
// here we are setting our data
// that means, take the data from the cursor and put it in views
double weight = cursor.getDouble(cursor
.getColumnIndex(DbHelper.ENTRY_USER_WEIGHT));
int count=cursor.getCount();
Double[] input = new Double[count];
// Obtaining the number of records
System.out.println("number of records "+input.length);
// Array for storing differences
double[] difference= new double[count ];
difference [0] = 0; // First record difference is 0 only
int i;
// Looping number of records times
for( i=0; i<count-1 ;i++)
{
input[i]=weight;
System.out.println("i value"+i);
System. out.println(""+input[i]);
// Difference = next record - current record
difference [i]= input [i+1] - input[i];
// System.out.println ("Difference between "+input [i+1]+ " and "+input[i] + " is : " +difference[i]);
}
// Setting the input array.
int input[]= {80, 82, 84, 90, 94};
// Obtaining the number of records
int noOfRecords = input.length;
// Array for storing differences
double[] difference= new double[noOfRecords ];
difference [0] = 0; // First record difference is 0 only
// Looping number of records times
for( int i=0; i < noOfRecords -1 ;i++)
{
// Difference = next record - current record
difference [i+1]= input [i+1] - input[i];
System.out.println ("Difference between "+input [i+1]+ " and "+input[i] + " is : " +difference[i+1]);
}
System.out.println("My final difference array Output is : "+java.util.Arrays.toString( difference ));
OUTPUT:
Difference between 82 and 80 is : 2.0
Difference between 84 and 82 is : 2.0
Difference between 90 and 84 is : 6.0
Difference between 94 and 90 is : 4.0
My final difference array Output is : [0.0, 2.0, 2.0, 6.0, 4.0]
If you replace double[] difference = new double[noOfRecords ]; by
int [] difference = new int [noOfRecords];
You get an output exactly as you wanted :
Difference between 82 and 80 is : 2
Difference between 84 and 82 is : 2
Difference between 90 and 84 is : 6
Difference between 94 and 90 is : 4
My difference array Output is : [0, 2, 2, 6, 4]
Logic:
for array Arr[] = {80 82 84 90 94}
Required output = {0,2,2,6,4}
Sol:
output[0] = 0;
for( i=1;i<cursor.getCount();i++)
{
output[i] = Arr[i]-Arr[i-1];
}
Note that the output array elements are obtained by subtracting current index element with the element at previous index.
Example 82-80 =2, 84-82=2, 90-84=6 and 94-90=4
You can subtract a number from its next number.
int[] numbers={80, 82, 84, 90, 94};
for (int i = 0; i < numbers.length; i++) {
if(i < numbers.length - 1)
System.out.println(numbers[i + 1] - numbers[i]);
}
}
Output-
2
2
6
4

Categories