I'm trying to convert some Octave functions to Java, but I'm not sure I'm this right.
function [y,a] = forwardProp(x, Thetas)
a{1} = x;
L = length(Thetas)+1;
for i = 2:L,
a{i-1} =[1; a{i-1}];
z{i} =Thetas{i-1}*a{i-1};
a{i} =sigmoid(z{i});
end
y = a{L};
end
My Java Function
public class ForwardProp {
public static DoubleMatrix ForwardProp(DoubleMatrix x, DoubleMatrix Thetas)
{
DoubleMatrix a = new DoubleMatrix();
a = DoubleMatrix.concatHorizontally(DoubleMatrix.ones(a.rows, 1), x);
int L = Thetas.length + 1;
DoubleMatrix z = new DoubleMatrix();
for (int i = 2; i <= L; i++)
{
a.put(i - 1, a.get(i - 1));
z.put(i, (Thetas.get(-1) * a.get(i - 1)));
a.put(i, Sigmoid(z.get(i)));
}
return a;
}
}
Can someone tell me if this is right???
As far as I can tell, you are committing a double-fencepost error here:
int L = Thetas.length + 1;
L now equals 1 more than the number of elements in the matrix...
for (int i = 2; i <= L; i++) ...and you are now looping with Thetas.get(i - 1) all the way up to an index that is 2 greater than the highest index available from Thetas.get(int).
Remember, Thetas.get(int) directly accesses the internal array that stores this matrix's data. This can only accept indices from 0 to Thetas.length - 1. So when you call Thetas.get(-1) you will always get an error because -1 is not a valid array index; when you get to the end of the loop and call Thetas.get(i - 1), you will get an error again because there is no element at that location.
You are also initializing your output matrix with DoubleMatrix z = new DoubleMatrix();, which returns a 0x0 empty matrix with no elements. That's not what you want either.
Try to make sure you know which indices your data is in, then rewrite it when you know how to reference the data you are using.
Related
a) Create an array of random numbers, whose size is a power of 2. Using loops, find the difference for each pair of values (index 0 & 1, 2 & 3, 4 & 5 etc.) and store them in a new array. Then find the difference for each pair of differences and so on until you have only one difference left.
Hint: Think carefully about your loop bounds
b) Now, create a solution that is 'in place', i.e., It does not require the creation of new arrays. Again, this will require careful consideration of loop bounds.
c) Finally, write a solution that makes use of a recursive function, instead of loops.
I have been trying to solve the above exercise but I am stuck with what b means and how can I use recursive function. The following is my solution for part a :
public class RandomArray{
private static double ArrayFn(int p){
double[] orignalArray = new double[(int)Math.pow(2,p)];
for (int i = 0; i< orignalArray.length; i++){
orignalArray[i] = (int)(Math.random() * 10) ;
}
System.out.println(Arrays.toString(orignalArray));
double y = ArrayDifferenceloop(orignalArray);
System.out.println("Value of Array" + y);
return y;
}
private static double ArrayDifferenceloop(double[] arg){
do{
double[] newArr = new double[(arg.length/2)];
for (int i = 0; i< arg.length; i+=2){
newArr[i/2] = arg[i] - arg[i+1];
}
System.out.println("New Array is =" + Arrays.toString(newArr));
//copy newArr to arg
arg = new double[(newArr.length)];
System.arraycopy(newArr,0,arg,0,newArr.length);
}while(arg.length > 1);
return arg[0];
}
public static void main(String[] args){
double z = ArrayFn(3);
System.out.println("value" + z);
}
}
I can help you with point b)
you can store the differences in the original array itself:
difference of [0] and [1] put in [0],
difference of [2] and [3] put in [1],
and so on.
You can calculate the index to put the result from the indexes of the pair or keep two index variables for the result and for picking the pairs.
you just keep iterate over the original array repeatedly, each time over fewer cells until only two cells left.
the recursive solution should be clear...
I guess option b means use the original array to store the differences, rather than creating a new array.
This can be achieved by dynamically changing the active range of elements used, ignoring others (see also Sharon Ben Asher answer ):
private static double ArrayDifferenceloop(double[] array){
int activeLength = array.length;
do{
int index =0; //index where to store difference
for (int i = 0; i< activeLength; i+=2){
array[index++] = array[i] - array[i+1];
}
System.out.println("Modified array (only "+index+ " elements are significant) " + Arrays.toString(array));
activeLength /=2;
}while(activeLength > 1);
return array[0];
}
/* Solution for part (b) hope it works for you*/
public class RandomArray{
static int len; /*modification*/
private static double ArrayFn(int p){
double[] orignalArray = new double[(int)Math.pow(2,p)];
len=(int)Math.pow(2,p);
for (int i = 0; i< orignalArray.length; i++){
orignalArray[i] = (int)(Math.random() * 10) ;
}
System.out.println(Arrays.toString(orignalArray));
double y = ArrayDifferenceloop(orignalArray);
System.out.println("Value of Array" + y);
return y;
}
private static double ArrayDifferenceloop(double[] arg){
do{
for (int i = 0; i< len; i+=2){ /*modification*/
arg[i/2] = arg[i] - arg[i+1];
}
//copy newArr to arg
//arg = new double[(arg.length)];
len=len/2; /*modification*/
System.out.print("new Array : ");
for(int i=0;i<len;i++){
System.out.print(arg[i]+" , ");
}
// System.arraycopy(arg,0,arg,0,len);
}while(len > 1);
return arg[0];
}
public static void main(String[] args){
double z = ArrayFn(3);
//System.out.println(Arrays.toString(orignalArray));
System.out.println("value" + z);
}
}
I'm getting an error on line 4 saying "forgot a .class, probably at the end." Can somebody please tell me what the solution is?
Side note - Java.util has been imported.
public double median(int[] arr)
{
int[] sortedArr = Arrays.sort(arr[]);
int arrayIndex = 0;
int halfArrayIndex = 0;
for(int i = 0; i < sortedArr.length; i++)
{
arrayIndex = i;
}
if(arrayIndex % 2 == 0)
{
halfArrayIndex = arrayIndex / 2;
return sortedArr[half];
}
else
{
halfArrayIndex = arrayIndex / 2;
return ((double)sortedArr[half + 1] + sortedArr[half]) / 2;
}
}
This line is incorrect:
int[] sortedArr = Arrays.sort(arr[]);
It should be:
Arrays.sort(arr);
Notice that:
Arrays.sort() doesn't return a value
You must not write [] when passing an array as parameter
When you sort an array, it'll be modified in-place, bear that in mind, because the original array passed as parameter to this method will be changed after this method returns, unless you make a copy of it
I'm doing a coding challenge online where I'm supposed to write a class that takes in a positive parameter ("num") and returns its multiplicative persistence. This is the number of times you must multiply the digits in "num" until you reach a single digit.
For example, the multiplicative persistence of 39 = 3. This is because:
3 * 9 = 27
2 * 7 = 14
1 * 4 = 4
This is the whole program so far:
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.List;
public class Persist {
public static void main(String[] args) {
persistence(39);
}
public static int persistence(long num) {
int persistenceValue = 0;
List<Long> digitList = new ArrayList<Long>();
long lastDigit;
//Resolves if num is single digit
if (num <= 9) {
return 0;
}
//Takes each digit of number and stores it to digitList (backwards)
while (num > 0) {
lastDigit = (num % 10);
digitList.add(lastDigit);
num = num / 10;
}
//Takes each digit in digitList and stores it in array in correct order
for (Long d : digitList) {
Long[] currentDigitArray = new Long[digitList.size()];
for (int i = 0; i < currentDigitArray.length; i++) {
currentDigitArray[currentDigitArray.length - i] = d;
}
persistenceValue = currentDigitArray.length;
while (persistenceValue > 1) {
List<Long> productList = multiplyDigits(currentDigitArray);
persistenceValue++;
}
}
return persistenceValue;
}
public static List multiplyDigits(Long[] currentDigitArray) {
//multiplies each digit
List<Long> productList = new ArrayList<Long>();
for (int i = 0; i < currentDigitArray.length; i++) {
Long product = currentDigitArray[i] * currentDigitArray[i + 1];
productList.add(product);
}
return productList;
}
}
I keep running into an array out of bounds exception for the for loop on line 52:
//Takes each digit in digitList and stores it in an array
for (Long d : digitList) {
Long[] currentDigitArray = new Long[digitList.size()];
for (int i = 0; i < currentDigitArray.length; i++) {
currentDigitArray[currentDigitArray.length - i] = d;
// ^ exception is thrown here ^
}
So obviously I looked this up on Google like a good stack overflow user. An array-index out of bounds exception is a Java exception thrown due to the fact that the program is trying to access an element at a position that is outside an array limit, hence the words "Out of bounds."
The problem is that I have no idea how big that array is going to be up front because it's all going to depend on how many digits are passed in by the user. I hard coded 39, but eventually I want the user to be able to put in as many as they want.
So how else would I takes each digit in digitList and store it in array?
This part has been resolved, but now I have a similar problem on line 78:
public static List multiplyDigits(Long[] currentDigitArray) {
//multiplies each digit
List<Long> productList = new ArrayList<Long>();
for (int i = 0; i < currentDigitArray.length; i++) {
Long product = currentDigitArray[i] * currentDigitArray[i + 1];
//^This line here
productList.add(product);
}
return productList;
}
I feel like this is a very similar problem, but don't quite know how to fix it.
This assignment
currentDigitArray[currentDigitArray.length - i] = d;
should be
currentDigitArray[currentDigitArray.length - 1 - i] = d;
to avoid the problem.
With this said, you can avoid arrays entirely by performing multiplication as you go. Recall that the order in which you do multiplication does not change the result. Therefore, you can start multiplication from the back of the number, and arrive at the same solution.
Arrays are zero-indexed, so currentDigitArray.length is always going to be out of bounds. In fact, because of the additive identity property, currentDigitArray.length - i is going to be currentDigitArray.length when i is 0. To fix this, just subtract an extra 1 in your index calculation:
currentDigitArray[currentDigitArray.length - i - 1] = d;
For your second problem, you iterate one element too many, and you need to stop one element earlier:
for (int i = 0; i < currentDigitArray.length - 1; i++) {
I'm trying to use this array I create in printGrid method throughout my program. Currently, I have to run this method, but the values change because of the math.random method nested in this method and I don't want it to. I just want to run this once and use the output throughout my method, is this possible?
What I've tried - I've tried to return the value of the mapArray (seen in code) and printing that out, I'm having issue with that. I've also tried isolating the math.random method in it's own method to calculate the value of the cookies, but my issue with that is that it only returns one value and I need a dynamic amount depending on the input of the x / y vars. Any suggestions?
public static char[][] printGrid(int x, int y) {
// int [][] mapArray = new int [x][y]; // Gets the information to print the array
mapArray = new char[x][y]; // Gets the information to print the array
double cookies = (x * y) * (.1); // Calculates the number of cookies per x / y input
// Storing '.' in all values of the array
for (int d = 0; d < x; d++) // Moved from below.
{
for (int j = 0; j < y; j++) {
mapArray[d][j] = '.';
}
System.out.println();
}
// Storing '0' in random values of the array and '<' at [0][0]
int c = 0;
for (c = 1; c <= cookies; c++) {
int cookiesPrintColumn = (int)(cookies * Math.random());
int cookiesPrintRow = (int)(cookies * Math.random());
mapArray[cookiesPrintColumn][cookiesPrintRow] = 'O';
mapArray[0][0] = '>';
}
// Copy loop from above to print the grid.
for (int d = 0; d < x; d++) {
for (int j = 0; j < y; j++) {
System.out.print(mapArray[d][j]);
return mapArray;
}
System.out.println();
}
return mapArray;
} // printGrid method close
If you are trying to create an array in a method, and then need to use in throughout your program, such as in main, you aren't going to be able to directly use that exact array because it will be out of scope. You can however create and then initialize the array in main equal to the return statement of your method. For example:
main() {
int[][] example;
example[][] = method(...);
}
int [][] method(...){
int[][] exampleArray = {1,2,3} // your random values here
return exampleArray;
}
Because you are creating the actual array inside of the method, it will not be in scope in main. This however will have the exact values the same, so the random numbers will be identical, and you can continue to use this for the rest of your program.
Use return value:
import package.ClassNane;
class Example {
int x = 1;
int y = 2;
char[][] grid = ClassName.printGrid(x, y);
}
I have source array, and I want to generate new array from the source array by removing a specified number of elements from the source array, I want the elements in the new array to cover as much as possible elements from the source array (the new elements are uniformly distributed over the source array) and keeping the first and last elements the same (if any).
I tried this :
public static void printArr(float[] arr)
{
for (int i = 0; i < arr.length; i++)
System.out.println("arr[" + i + "]=" + arr[i]);
}
public static float[] removeElements(float[] inputArr , int numberOfElementToDelete)
{
float [] new_arr = new float[inputArr.length - numberOfElementToDelete];
int f = (inputArr.length ) / numberOfElementToDelete;
System.out.println("f=" + f);
if(f == 1)
{
f = 2;
System.out.println("f=" + f);
}
int j = 1 ;
for (int i = 1; i < inputArr.length ; i++)
{
if( (i + 1) % f != 0)
{
System.out.println("i=" + i + " j= " + j);
if(j < new_arr.length)
{
new_arr[j] = inputArr[i];
j++;
}
}
}
new_arr[0] = inputArr[0];
new_arr[new_arr.length - 1] = inputArr[inputArr.length - 1];
return new_arr;
}
public static void main(String[] args)
{
float [] a = {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16};
a = removeElements(a, 6);
printArr(a);
}
I have made a test for(removeElements(a, 5) and removeElements(a, 4) and removeElements(a, 3)) but removeElements(a, 6); gave :
arr[0]=1.0
arr[1]=3.0
arr[2]=5.0
arr[3]=7.0
arr[4]=9.0
arr[5]=11.0
arr[6]=13.0
arr[7]=15.0
arr[8]=0.0
arr[9]=16.0
the problem is (arr[8]=0.0) it must take a value ..
How to solve this? is there any code that can remove a specified number of elements (and keep the elements distributed over the source array without generating zero in some elements)?
EDIT :
examples :
removeElements(a, 1) ==> remove one element from the middle (7) {1,2,3,4,5,6,7,9,10,11,12,13,14,15,16}
removeElements(a, 2) ==> remove two elements at indexes (4,19) or (5,10) or (4,10) (no problem)
removeElements(a, 3) ==> remove three elements at indexes (4,9,14) or (4,10, 15) or(no problem also)
removeElements(a, 4) ==> remove four elements at indexes (3,7,11 , 15) or ( 3 ,7,11,14) for example ..
what I want is if I draw the values in the source array on (chart on Excel for example) and I draw the values from the new array , I must get the same line (or close to it).
I think the main problem in your code is that you are binding the selection to
(inputArr.length ) / numberOfElementToDelete
This way you are not considering the first and the last elements that you don't want to remove.
An example:
if you have an array of 16 elements and you want to delete 6 elements it means that the final array will have 10 elements but, since the first and the last are fixed, you'll have to select 8 elements out of the remaining 14. This means you'll have to select 8/14 (0,57) elements from the array (not considering the first and the last).
This means that you can initialize a counter to zero, scan the array starting from the second and sum the value of the fraction to the counter, when the value of the counter reach a new integer number (ex. at the third element the counter will reach 1,14) you'll have an element to pick and put to the new array.
So, you can do something like this (pseudocode):
int newLength = originalLength - toDelete;
int toChoose = newLength - 2;
double fraction = toChoose / (originalLength -2)
double counter = 0;
int threshold = 1;
int newArrayIndex = 1;
for(int i = 1; i < originalLength-1; i++){
**counter += fraction;**
if(integerValueOf(counter) == threshold){
newArray[newArrayIndex] = originalArray[i];
threshold++;
**newArrayIndex++;**
}
}
newArray[0] = originalArray[0];
newArray[newArray.length-1] = originalArray[originalArray.length-1];
You should check for the particular cases like originalArray of length 1 or removal of all the elements but I think it should work.
EDIT
Here is a Java implementation (written on the fly so I didn't check for nulls etc.)
public class Test {
public static void main(String[] args){
int[] testArray = {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16};
int[] newArray = remove(testArray, 6);
for(int i = 0; i < newArray.length; i++){
System.out.print(newArray[i]+" ");
}
}
public static int[] remove(int[] originalArray, int toDelete){
if(toDelete == originalArray.length){
//avoid the removal of all the elements, save at least first and last
toDelete = originalArray.length-2;
}
int originalLength = originalArray.length;
int newLength = originalLength - toDelete;
int toChoose = newLength - 2;
int[] newArray = new int[newLength];
double fraction = ((double)toChoose) / ((double)originalLength -2);
double counter = 0;
int threshold = 1;
int newArrayIndex = 1;
for(int i = 1; i < originalLength-1; i++){
counter += fraction;
if(((int)counter) == threshold ||
//condition added to cope with x.99999999999999999... cases
(i == originalLength-2 && newArrayIndex == newLength-2)){
newArray[newArrayIndex] = originalArray[i];
threshold++;
newArrayIndex++;
}
}
newArray[0] = originalArray[0];
newArray[newArray.length-1] = originalArray[originalArray.length-1];
return newArray;
}
}
Why cant you just initialize i=0
for (int i = 0; i < inputArr.length; i++) {
if ((i + 1) % f != 0) {
Following is the output:
arr[0]=1.0
arr[1]=1.0
arr[2]=3.0
arr[3]=5.0
arr[4]=7.0
arr[5]=9.0
arr[6]=11.0
arr[7]=13.0
arr[8]=15.0
arr[9]=16.0
This is Reservoir sampling if I understand it right i.e from a large array, create a small array by randomly choosing.