CopyOf returning array - java

jump is an array that has been initialised.
FunctionMonius3.difRandoms method returns an array
jump = FunctionMonius3.difRandoms(posMonius.length, lines * col, generator);
or
jump = Arrays.copyOf(FunctionMonius3.difRandoms(posMonius.length, lines * col, generator), v.length);
Does the first option just creates a reference that is destroyed when the method FunctionMonius3.difRandoms ends or is it ok?
* #param n - number of array elements
* #param sup - max value
* #param g - generator
public static int[] difRandom (int n, int sup, Random g){
int[] result = new int [n];
int i = 0;
while (i < result.length) {
int random = g.nextInt(sup) + 1;
if (!contidoEmParte(aleatorio,result,i)){
result[i] = random;
i++;
}
}
return result;
}

Related

Why is my stack only adding one element and then it deletes it?

I already debugged the code and found, that it adds the fist element (Stack size = 1)
but when trying to add the next element, the stack size jumps back to 0
I think the problem is in public void convert.
public void convert(int N) {
this.N = N;
int binary[] = new int[10];
int index = 0;
while (N > 0) {
binary[index++] = N % 2;
N = N / 2;
}
for (int x = index - 1; x >= 0; x--) {
this.binStack.push(binary[x]); //Here is the Problem
}
}
This is the whole code:
import java.util.Stack;
public class Dec2Bin {
public Stack<Integer> binStack; // We make it public to modify it in our tests.
private int N;
/**
* Constructor of an empty object. Use method {#code convert()} to convert a number.
*/
public Dec2Bin() {
binStack = new Stack<>();
}
/**
* Returns the number that is converted as {#code int}.
*
* #return the converted number
*/
public int getN() {
return N;
}
/**
* Converts the given number into binary format, with each digit being represented in a
* stack of {#code int}.
*
* #param N the number that is to be converted.
*/
public void convert(int N) {
// TODO implement this method
this.N = N;
int binary[] = new int[10];
int index = 0;
while (N > 0) {
binary[index++] = N % 2;
N = N / 2;
}
for (int x = index - 1; x >= 0; x--) {
this.binStack.push(binary[x]);
}
}
/**
* Returns the digits that are stored in {#code binStack} as a string. To is the binary format of the
* converted number.
* For testing purpose, we require that the function works also, if the variable {#code binStack} is
* modified externally.
*
* #return a string representation of the number in binary format.
*/
#Override
public String toString() {
// Caution: Stack.toString() does NOT respect stack order. Do not use it.
// TODO implement this method
String finalBinär = new String();
for (int y = 0; y < binStack.size(); y++){
String binär = Integer.toString(binStack.pop());
String prevBinär = new String();
finalBinär = prevBinär.concat(binär);
}
return finalBinär;
}
public static void main(String[] args) {
Dec2Bin dec2bin = new Dec2Bin();
dec2bin.convert(50);
System.out.println("Die Zahl " + dec2bin.getN() + " in Binärdarstellung: " + dec2bin);
// Do it another time to demonstrate that toString does not erase the binStack.
System.out.println("Die Zahl " + dec2bin.getN() + " in Binärdarstellung: " + dec2bin);
}
}
´´´
import java.util.Stack;
public class Dec2Bin {
public Stack<Integer> binStack; // We make it public to modify it in our tests.
private int N;
/**
* Constructor of an empty object. Use method {#code convert()} to convert a number.
*/
public Dec2Bin() {
binStack = new Stack<>();
}
/**
* Returns the number that is converted as {#code int}.
*
* #return the converted number
*/
public int getN() {
return N;
}
/**
* Converts the given number into binary format, with each digit being represented in a
* stack of {#code int}.
*
* #param N the number that is to be converted.
*/
public void convert(int N) {
// TODO implement this method
this.N = N;
int binary[] = new int[10];
int index = 0;
while (N > 0) {
binary[index++] = N % 2;
N = N / 2;
}
for (int x = index - 1; x >= 0; x--) {
this.binStack.push(binary[x]);
}
}
/**
* Returns the digits that are stored in {#code binStack} as a string. To is the binary format of the
* converted number.
* For testing purpose, we require that the function works also, if the variable {#code binStack} is
* modified externally.
*
* #return a string representation of the number in binary format.
*/
#Override
public String toString() {
// Caution: Stack.toString() does NOT respect stack order. Do not use it.
// TODO implement this method
String finalBinär = new String();
for (int y = 0; y < binStack.size(); y++){
String binär = Integer.toString(binStack.pop());
String prevBinär = new String();
finalBinär = prevBinär.concat(binär);
}
return finalBinär;
}
public static void main(String[] args) {
Dec2Bin dec2bin = new Dec2Bin();
dec2bin.convert(50);
System.out.println("Die Zahl " + dec2bin.getN() + " in Binärdarstellung: " + dec2bin);
// Do it another time to demonstrate that toString does not erase the binStack.
System.out.println("Die Zahl " + dec2bin.getN() + " in Binärdarstellung: " + dec2bin);
}
}
´´´
Your toString() method has at least two problems:
#Override
public String toString() {
// Caution: Stack.toString() does NOT respect stack order. Do not use it.
// TODO implement this method
String finalBinär = new String();
for (int y = 0; y < binStack.size(); y++){ // <1>
String binär = Integer.toString(binStack.pop()); // <2>
String prevBinär = new String();
finalBinär = prevBinär.concat(binär); // <3>
}
return finalBinär;
}
Lines <1> and <2>: during the for loop y is incremented on line <1>. At the same time the stack size decreases because on line <2> you remove elements from the stack with binStack.pop().
That means that you will only get about half the digits. (For example, if binStack.size() was 6 at the start: after 3 runs through the loop y == 3 and binStack.size() == 3, so your loop will terminate.)
Line <3> means that no matter what was in the binStack, your result will only ever contain one binary digit: that line (together with the previous line) has the same effect as finalBinär = ""+binär;, which effectively means: finalBinär = binär;

error: illegal start of expression; reached end of file while parsing

I'm new to Java programming. This is part of homework questions. I need to provide a set of comparison methods on arrays. I tried my best and this is my attempt so far. Can somebody enlighten me? Any help will be much appreciated!
Several requirements I need to follow:
You must not add any public methods to the Selector class. You are free to add any private methods that you think are appropriate, but you can't add any public methods.
You must not add any fields, either public or private, to the Selector class.
You must not import anything other than java.util.Arrays, but you are not required to import this at all.
You are only allowed to use sorting as part of your solution in the nearest and farthest
methods.
You must not modify the existing constructor or add other constructors. This class is designed to be strictly a provider of static methods and should not be instantiated.
import java.util.Arrays;
/**
* A class that contains various selection methods on arrays.
* All methods assume that the array is completely filled with
* non-null values. If this is not true, the behavior is not specified.
* All the methods throw an IllegalArgumentException if the array
* parameter is null or has zero length. The array parameter to
* each method is guaranteed to not be changed as a result of the call.
*/
public final class Comparision{
/**
* C A N N O T I N S T A N T I A T E T H I S C L A S S .
*
*/
private Comparision(){
}
/**
* Return the element of a nearest to val. This method throws an
* IllegalArgumentException if a is null or has zero-length.
* The array a is not changed as a result of calling this method.
*
* #param a the array to be searched
* #param val the reference value
* #return the element a[i] such that ABS(a[i] - val) is minimum
*
*/
public static int nearest(int[] a, int val) {
int[] a = new int[10];
if (a == null || a.length == 0){
throw new IllegalArgumentException("a is null or has zero-length");
}
int idx = 0;
int distance = Math.abs(a[0]-val);
for(int c = 1; c< a.length; c++){
int cdistance = Math.abs(a[c] - val);
if(cdistance < distance){
idx=c;
distance = cdistance;
}
}
int theNumber = a[idx];
return theNumber;
}
/**
* Return the element of a farthest from val. This method throws an
* IllegalArgumentException if a is null or has zero-length.
* The array a is not changed as a result of calling this method.
*
* #param a the array to be searched
* #param val the reference value
* #return the element a[i] such that ABS(a[i] - val) is maximum
*
*/
public static int farthest(int[] a, int val) {
int[] a = new int[10];
if (a == null || a.length == 0){
throw new IllegalArgumentException("a is null or has zero-length");
}
int idx = 0;
int distance = Math.abs(a[0]-val);
for(int c = 1; c< a.length; c++){
int cdistance = Math.abs(a[c] - val);
if(cdistance > distance){
idx=c;
distance = cdistance;
}
}
int theNumber = a[idx];
return theNumber;
}
/**
* Return the k elements of a nearest to val.
* The array a is not changed as a result of calling this method.
* This method throws an IllegalArgumentException if k is negative.
* This method returns an array of zero length if k == 0 or if
* k > a.length.
*
* #param a the array to be searched
* #param val the reference value
* #param k the number of near elements to identify
* #return the k elements a[i] such that ABS(a[i] - val)
* are the k smallest evaluations
*
*/
public static int[] nearestK(int[] a, int val, int k) {
int[] b = new int[10];
for (int i = 0; i < b.length; i++){
b[i] = Math.abs(a[i] - val);
}
Arrays.sort(b);
int[] c = new int[w];
w = 0;
for (int i = 0; i < k; i++){
if (k < 0){
throw new IllegalArgumentException("k is not invalid!");
}
c[w] = b[i];
w++;
}
return c;
}
/**
* Return the k elements of a farthest from val.
* The array a is not changed as a result of calling this method.
* This method throws an IllegalArgumentException if k is negative.
* This method returns an array of zero length if k == 0 or if
* k > a.length.
*
* #param a the array to be searched
* #param val the reference value
* #param k the number of far elements to identify
* #return the k elements a[i] such that ABS(a[i] - val)
* are the k largest evaluations
*
*/
public static int[] farthestK(int[] a, int val, int k) {
int[] b = new int[10];
for (int i = 0; i < 10; i++){
b[i] = Math.abs(a[i] - val);
}
Arrays.sort(b);
int[] c = new int[w];
int w = 0;
for (int i = array.length-1; i >= array.length-k; i--){
if (k < 0){
throw new IllegalArgumentException("k is not invalid!");
}
else if (k == 0 || k > a.length){
int[] c = "";
}
c[w] = b[i];
w++;
}
return c;
}
/**
* Return the number of elements of a that are greater than val.
*
* #param a the array to be searched
* #param val the reference value
* #return the number of elements a[i] such that a[i] > val
*
*/
public static int numGreater(int[] a, int val) {
int w = 0;
for (int i = 0; i < a.length; i++){
if ((a[i] - val)>0){
w++;
}
return w;
}
/**
* Return an array of all the elements of a that are greater than val.
* If a contains no elements greater than val, this method returns an
* array of zero length.
*
* #param a the array to be searched
* #param val the reference value
* #return the elements a[i] such that a[i] > val
*
*/
public static int[] greater(int[] a, int val){
int[] b = new int[w];
int w = 0;
for (int i = 0; i < a.length; i++){
if ((a[i] - val)>0){
b[w] = a[i];
w++;
}
}
if (w = 0){
int[] b = {};
}
return b;
}
/**
* Return the number of elements of a that are less than val.
*
* #param a the array to be searched
* #param val the reference value
* #return the number of elements a[i] such that a[i] < val
*
*/
public static int numLess(int[] a, int val) {
int w = 0;
for (int i = 0; i < a.length; i++){
if ((a[i] - val)<0){
w++;
}
return w;
}
/**
* Return an array of all the elements of a that are less than val.
* If a contains no elements less than val, this method returns an
* array of zero length.
*
* #param a the array to be searched
* #param val the reference value
* #return the elements a[i] such that a[i] < val
*
*/
public static int[] less(int[] a, int val) {
int[] b = new int[w];
int w = 0;
for (int i = 0; i < a.length; i++){
if ((a[i] - val)<0){
b[w] = a[i];
w++;
}
}
if (w = 0){
int[] b = {};
}
return b;
}
}
You problem is in lines 194-197: you aren't closing your if statement, so your close curly braces after that are all messed up. To fix it, change numLess to:
public static int numLess(int[] a, int val) {
int w = 0;
for (int i = 0; i < a.length; i++){
if ((a[i] - val)<0){
w++;
} // This is the curly brace you are missing
}
return w;
}
EDIT: the other answer is right as well; you have the same problem in both numGreater and numLess. Add the close-curly brace in both functions and it should compile correctly.
I think you're missing brackets or semi-colons:
This should be:
public static int numGreater(int[] a, int val) {
int w = 0;
for (int i = 0; i < a.length; i++){
if ((a[i] - val)>0){
w++;
}
return w;
}
Should be:
public static int numGreater(int[] a, int val) {
int w = 0;
for (int i = 0; i < a.length; i++){
if ((a[i] - val)>0){
w++;
}//<---missing this fella
}
return w;
}

Quicksort partition algorithm loop invariants defined in partition method

I implemented the partition method in the quicksort algorithm but i dont know if it satisfies the loop invariant that they were given to me.
public class qs {
private qs(){}
/**
* Sort an array in ascending order
* #param arr array to sor */
public static void quickSort(int[] arr){
qs(arr, 0, arr.length);
}
/**
* Sort a region of an array in ascending order.
* Elements outside the given region are unchanged.
* requires: 0 <= start <= end <= arr.length
* #param arr array to sort
* #param start start of region (inclusive)
* #param end end of region (exclusive)
*/
private static void qs(int[] arr, int start, int end){
if (end <= start+1){ //region of length 0 or 1
return;
}
int x = arr[start];
int p = partition(arr, start+1, end, x);
//now swap arr[start] with arr[p-1]
arr[start] = arr[p-1];
arr[p-1] = x;
qs(arr, start, p-1);
qs(arr, p, end);
}
/**
* Partition a region of an array.
* Rearranges elements in region so that small ones
* all have smaller indexes than the big ones.
* Elements outside the region are unchanged.
* requires: 0 <= start <= end <= arr.length
* #param arr array to partition
* #param start start of region (inclusive)
* #param end end of region (exclusive)
* #param x pivot - "small" and "big" are <x, >=x.
* #return start index (inclusive) of big elements
* in region after partition.
*/
private static int partition(
int[] arr, int start, int end, int x)
{
int l = start-1 ;
int r = end;
while (true) {
while(++l< r && arr[l] < x);
while(r-- > l && arr[r] > x);// find smaller item
if(l >= r) // if pointers cross,
break; // partition done
else {
int temp;
temp = arr[l];
arr[l] = arr[r];
arr[r] = temp;
}
}
return l;
}
public static void main(String[] args) {
int[] a = {15,8,4,8,9,6,4,1,2,5,6,4};
quickSort(a);
for (int i = 0; i < a.length; i++){
System.out.print(" "+a[i]);
}
}
}
Your code should work except one problem. Pivot that you are selecting is the starting point of the array rather than a middle point of the array. So instead assigning
int x = arr[start];
You better assign it to
int x = arr[(start + end)/2];
Your code must work.

Java quicksort.Identify changes in the partition while loop

What changes do i need to make to the partition loop if inside the partition method i want to initialise l=start or l=start+1 and end =end-1 ? If these values are initialised to l=start-1; and r=end; than the loop works fine but it does not satisfy the invariant.Any ideas?
public class qs {
private qs(){}
/**
* Sort an array in ascending order
* #param arr array to sor */
public static void quickSort(int[] arr){
qs(arr, 0, arr.length);
}
/**
* Sort a region of an array in ascending order.
* Elements outside the given region are unchanged.
* requires: 0 <= start <= end <= arr.length
* #param arr array to sort
* #param start start of region (inclusive)
* #param end end of region (exclusive)
*/
private static void qs(int[] arr, int start, int end){
if (end <= start+1){ //region of length 0 or 1
return;
}
int x = arr[start];
int p = partition(arr, start+1, end, x);
//now swap arr[start] with arr[p-1]
arr[start] = arr[p-1];
arr[p-1] = x;
qs(arr, start, p-1);
qs(arr, p, end);
}
/**
* Partition a region of an array.
* Rearranges elements in region so that small ones
* all have smaller indexes than the big ones.
* Elements outside the region are unchanged.
* requires: 0 <= start <= end <= arr.length
* #param arr array to partition
* #param start start of region (inclusive)
* #param end end of region (exclusive)
* #param x pivot - "small" and "big" are <x, >=x.
* #return start index (inclusive) of big elements
* in region after partition.
*/
private static int partition(
int[] arr, int start, int end, int x)
{
int l = start ;
int r = end-1;
while (l<r) {
while(++l< r && arr[l] < x);
while(--r > l && arr[r] > x);
if(l >= r) // if pointers cross,
break; // partition done
else {
int temp;
temp = arr[l];
arr[l] = arr[r];
arr[r] = temp;
}
}
return l;
}
public static void main(String[] args) {
int[] a = {15,8,4,8,9,6,};
quickSort(a);
for (int i = 0; i < a.length; i++){
System.out.print(" "+a[i]);
}
}
}
Pivot should be Middle point, not the starting of the array.
int x = arr[start];
Replace this line with this...
int x = arr[(start+end)/2]

How to convert a 1d array to 2d array?

Say, I have a 1d array with 30 elements:
array1d[0] = 1
array1d[1] = 2
array1d[2] = 3
.
.
.
array1[29] = 30
How to convert the 1d array to 2d array?
Say 10x3?
array2d[0][0] = 1 array2d[0][1] =2 array2d[0][2] =3
.
.
.
array2d[9][0] = 28 array2d[9][1] =29 array2d[9][2] =30
Should I use a for loop?
But I cannot work it out.
Without writing any code for you...
Think about how big your 2d array needs to be.
Recognize that you'll need to loop over the contents of your source array to get each value into your destination array.
So it will look something like...
Create a 2d array of appropriate size.
Use a for loop to loop over your 1d array.
Inside that for loop, you'll need to figure out where each value in the 1d array should go in the 2d array. Try using the mod function against your counter variable to "wrap around" the indices of the 2d array.
I'm being intentionally vague, seeing as this is homework. Try posting some code so we can see where you get stuck.
int array2d[][] = new int[10][3];
for(int i=0; i<10;i++)
for(int j=0;j<3;j++)
array2d[i][j] = array1d[(j*10) + i];
Here a generic function to convert from 1D -> 2D array:
public int[][] monoToBidi( final int[] array, final int rows, final int cols ) {
if (array.length != (rows*cols))
throw new IllegalArgumentException("Invalid array length");
int[][] bidi = new int[rows][cols];
for ( int i = 0; i < rows; i++ )
System.arraycopy(array, (i*cols), bidi[i], 0, cols);
return bidi;
}
If you want to do the contrary (2D -> 1D), here the function:
public int[] bidiToMono( final int[][] array ) {
int rows = array.length, cols = array[0].length;
int[] mono = new int[(rows*cols)];
for ( int i = 0; i < rows; i++ )
System.arraycopy(array[i], 0, mono, (i*cols), cols);
return mono;
}
public class Test{
public static void main(String[] argv)
{
int x,y;
for(int num =0; num<81;num++)
{
if((num % 9)>0)
{
x = num/9;
y = num%9;
}else
{
x = num/9;
y = 0;
}
System.out.println("num ["+num+"]---["+x+","+y+"]");
}
}
}
/* Replace 9 by the size of single row of your 2D array */
You often will find the same problem: how to manipulate 2D array as 1D array.
I wrote a generic class Grid, that lets access objects by index or by (x,y).
See the following class and understand the idea behind it. :)
You could use the following class for data manipulation as 2D array or 1D array. Here is the code for that I wrote and use.
/**
* Grid represents a 2 dimensional grid.
*
* #param <E> the type of elements in this grid
*/
import java.util.List;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
public class Grid<E>
{
private int size ;
private int width ;
private int height ;
private List<E> elements;
public int getCapacity()
{
return getWidth() * getHeight();
}
/**
* #return number of elements in grid. Null is also an element.
*/
public int getSize()
{
return getElements().size();
}
/**
* #param sideSize size of the grid side
*/
public Grid(int sideSize)
{
this(sideSize,sideSize);
}
/**
* #param width of the grid
* #param height of the grid
*/
public Grid(int width, int height)
{
this.width = width ;
this.height = height;
this.elements = new ArrayList<E>(
Collections.nCopies(width*height, (E)null));
}
public int getHeight()
{
return height;
}
public int getWidth()
{
return width;
}
/**
* #return all elements of the grid
*/
public List<E> getElements()
{
return elements;
}
/**
* #return iterator for a grid
*/
public Iterator<E> iterator()
{
return getElements().iterator();
}
/**
* Returns the element at position (x,y).
*
* #return the element at position (x,y)
*/
public E get(int x, int y)
{
return getElements().get(
idx(x,y));
}
/**
* Returns the element at index idx.
*
* #return the element at given index
*/
public E get(int idx)
{
return getElements().get(idx);
}
/**
* Puts an element to the position idx
*
* #param element to be added
*
* #param x position x to add element to
*
* #param y position y to add element to
*/
public void put(int x, int y, E element)
{
put(idx(x,y), element);
}
/**
* Puts an element to the position idx
*
* #param element to be added
*
* #param idx to add element at
*/
public void put(int idx, E element)
{
getElements().add(idx, element);
}
/**
* Returns the x coordinate from the index.
*
* #return x coordinate of the index
*/
public int x(int idx)
{
return idx % getHeight();
}
/**
* Returns the y coordinate from the index.
*
* #return y coordinate of the index
*/
public int y(int idx)
{
return (idx - idx % getHeight()) / getHeight();
}
/**
* Returns index of element at (x,y).
*
* #return index of the coordinates
*/
public int idx(int x, int y)
{
return y*getHeight() + x;
}
}
Here is how to use the class (see a test example):
public class TestGrid
{
public static final int SIZE = 10;
public static final Integer el1 = new Integer(2);
public static final Integer el2 = new Integer(3);
public static final Integer el3 = new Integer(3);
public static void main(String[] args)
{
Grid<Integer> grid = new Grid<>(SIZE);
assert grid.getCapacity() == SIZE*SIZE ;
assert grid.idx(0,0) == 0 ;
assert grid.idx(1,0) == 1 ;
assert grid.idx(0,1) == 10;
assert grid.idx(6,1) == 16;
assert grid.idx(9,9) == 99;
grid.put(1, el1);
assert grid.get(1) == el1 : grid.get(1);
grid.put(0, 1, el2);
assert grid.get(0,1) != el1 && el1 != el2 && grid.get(0,1) == el2;
grid.put(15, el3);
assert grid.get(5,1) == el3;
}
}
This is just a pseudo code. ROWS represent the length of the 2d array, and COLUMNS represent the length of the 1st element in the array
for(i=0; i<ROWS; i++)
for(j=0; j<COLUMNS; j++)
array2d[i][j] = array1d[ (i*COLUMNS) + j];
package com.vikrant;
import java.util.Arrays;
public class TwoD {
public static void main(String args[])
{
int a[][]=new int[4][3];
int d[]={10,20,30,40,50,60,70,80,90,100,110,120};
int count=0;
for(int i=0;i<4;i++)
{
for(int j=0;j<3;j++)
{
if(count==d.length) break;
a[i][j]=d[count];
count++;
}}
int j=0;
for (int i = 0; i<4;i++)
{
for(j=0;j<3;j++)
System.out.println(a[i][j]);
}
}}
THIS DOES THE WORK
int[] oneDArray = new int[arr.length*arr.length];
//Flatten 2D array to 1D array...
int s = 0;
for(int i = 0; i < arr.length; i ++)
for(int j = 0; j < arr.length; j ++){
oneDArray[s] = arr[i][j];
s++;
}
You can't "convert" a 1D array to a 2D array, but an array can be multi-dimensionnal when you declare it.
int myArray2d[][] = new int[10][3]

Categories

Resources