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
Related
I am a beginner(first year uni student) programmer trying to solve this problem which i'm finding somewhat difficult. If you are to answer this question, don't provide me with a complex daunting algorithm that will leave me scratching my head. I'll really appreciate it if you explain it step my step (both logically/conceptually then through code)
The problem is as follows:image
I have tried to attempt it and my code only works for a certain case that i tested.
package com.company;
import java.lang.Math;
public class Main {
public static int[][] binary_partition(int array[], int k){
int x = (int) Math.pow(2,k);
int[][] partition = new int[((array.length/x)*2)][array.length/x];
int divisor = array.length/x;
if ((array.length % 2) != 0){
return partition;
}
if (divisor >= array.length-1){
return partition;
}
if (k==1){
return partition;
}
int p = 0;
for(int i=0;i<((array.length/x)*2);i++)
{
for (int j = 0; j<array.length/x;j++)
{
partition[i][j] = array[p];
p += 1;
}
}
return partition;
}
public static void main(String[] args){
int[] array = {3, 2, 4, 7, 8, 9, 2, 3};
int[][] result = binary_partition(array,2);
for (int[] x : result){
for (int y : x)
{
System.out.print(y + " ");
}
System.out.println();
}
}
}
Your question is unclear, but this solution creates a function that partitions an array with the right length into 2^k sets.
First, an interesting fact: using the bitshift operator << on an integer increases its value by a power of two. So to find out the size of your partition, you could write
int numPartitions = 1 << k; // Equivalent to getting the integer value of 2^k
With this fact, the function becomes
public static int[][] partition(int[] set, int k) {
if (set == null)
return null; // Don't try to partition a null reference
// If k = 0, the partition of the set is just the set
if (k == 0) {
int[][] partition = new int[1][set.length];
// Copy the original set into the partition
System.arraycopy(set, 0, partition[0], 0, set.length);
return partition;
}
int numPartitions = 1 << k; // The number of sets to partition the array into
int numElements = set.length / numPartitions; // The number of elements per partition
/* Check if the set has enough elements to create a partition and make sure
that the partitions are even */
if (numElements == 0 || set.length % numElements != 0)
return null; // Replace with an error/exception of your choice
int[][] partition = new int[numPartitions][numElements];
int index = 0;
for (int r = 0; r < numPartitions; r++) {
for (int c = 0; c < numElements; c++) {
partition[r][c] = set[index++]; // Assign an element to the partition
}
}
return partition;
}
There are a few lines of your code where the intention is not clear. For example, it is not clear why you are validating divisor >= array.length-1. Checking k==1 is also incorrect because k=1 is a valid input to the method. In fact, all your validation checks are not needed. All you need to validate is that array.length is divisible by x.
The main problem that you have seems to be that you mixed up the lengths of the resulting array.
The resulting array should have a length of array.length / x, and each of the subarrays should have a length of x, hence:
int[][] partition = new int[array.length/x][x];
If you also fix your bounds on the for loops, your code should work.
Your nested for loop can be rewritten as a single for loop:
for(int i = 0 ; i < array.length ; i++)
{
int index = i / x;
int subArrayIndex = i % x;
partition[index][subArrayIndex] = array[i];
}
You just need to figure out which indices a an element array[i] belongs by dividing and getting the remainder.
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 having an issue with using the foreach loop to find the index of the largest number in an array.
I am getting: "Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5"
I would really appreciate it if someone could help me out. Thanks! Here is my code:
public static int enhanIntMax(int[] a){
int largeIndex =0;
int largeArrnum=scores[0];
for( int i : a){
if(a[i] >largeArrnum){``
largeArrnum += a[i];
largeIndex += i;
}
}
return largeIndex;
}
public static void main(string[] args){
int[] a={1,2,3,4,5};
System.out.println(enhanInMax(a));
}
I'm sure you've worked it out from the comments, but the trouble here is :
if(a[i] > largeArrnum)
won't try to compare the element with the value of i against largeArrnum, but rather the ith element of a. By using an enhanced for loop, the "for(int i = 0; i < blah blah blah... " part of the loop is handled for you. Rather than iterate across the indices of the array, an enhanced loop iterates across its contents. Therefore, if at any point a value of a[i] is greater than the length, you'll get this error. The right way to fix it is to just replace "a[i]" with "i", but you might want to give this site a quick review first:
https://blogs.oracle.com/CoreJavaTechTips/entry/using_enhanced_for_loops_with
The for-each loop doesn't give you a means to directly access the current index. So you'd have to track it yourself. For example, with p and something like
public static int enhanIntMax(int[] a) {
int p = 0, largeIndex = 0, largeArrnum = a[0];
for (int i : a) { // <-- for each int i in a
if (i > largeArrnum) { // <-- if the value is greater then
largeArrnum = i; // <-- update the value
largeIndex = p; // <-- update the largest index
}
p++; // <-- update the position p.
}
return largeIndex; // <-- return the largest index.
}
Note That this is both easier to read and also slightly more efficient (because it skips comparing element 0 with itself) with a regular for loop like
public static int enhanIntMax(int[] a) {
int largeIndex = 0, largeArrnum = a[0];
for (int p = 1; p < a.length; p++) {
if (a[p] > largeArrnum) {
largeArrnum = a[p];
largeIndex = p;
}
}
return largeIndex;
}
With Java 8 you can now use:
int maxint = Arrays.stream(A)
.max()
.getAsInt();
int index = Arrays.asList(A).indexOf(maxInt);
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.
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.