My goal is to create an adjacency matrix generator (the only value elements can have is 0 or 1; it has to be symmetric, meaning element in [i][j] == element [j][i]) in Java.
I have some code, but the result is an nx5 matrix (if I establish n = 13, the resulting matrix is a 13x5 matrix). It is symmetric and the values of elements is bounded between 0-1, so that is not an issue. Another problem is I don't really know how to have an array without doubles, which is more of an aesthetical problem + ideally, the diagonal would be filled with "-" instead of zeroes, as it is now.
Random random = new Random();
double[][] array = new double[n][n];
for (int i = 0; i < array.length; i++)
{
for (int j = 0; j <= i; j++)
{
int x = random.nextInt(2);
array[i][j] = x;
if (i != j)
{
array[j][i] = x;
}
}
}
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
if (i == j || (i + j + 1) == n)
{
array[i][j] = 0;
}
}
}
for (double[] a : array)
{
System.out.println(Arrays.toString(a));
}
}
Related
Just a simple question. I know to print all possible pairs, you do a nested for loop with a few more adjustments to be fancier. In my case, I want to take it a step up where pairs are not allowed to repeat or have 2 of the same integer in a pair.
For example: (0,0) is not allowed, but (0,1) is allowed. If (0,1) is a pair, then (1,0) is not allowed.
If I had integers "0,1,2,3", then my output would be
(0,0)(0,1)(0,2)(0,3)(1,2)(1,3)(2,3)
This is my current code that won't print pairs with 2 same integers, but repeated pairs still print.
for(int a = 0; a < 4;a++) {
numbers.add(a);
}
for(int i = 0; i < 4; i++) {
for(int j = 0; j < 4; j++) {
if(i != j) {
System.out.println("("+i+" , "+j+")");
}
}
}
Thanks
for(int i = 0; i < 4; i++) {
for(int j = i; j < 4; j++) {
if(i != j) {
System.out.println("("+i+" , "+j+")");
}
}
}
or
for(int i = 0; i < 4; i++) {
for(int j = i + 1; j < 4; j++) {
System.out.println("("+i+" , "+j+")");
}
}
public static void main(String[] args) {
// TODO code application logic here
int numRows = 5;
int numCols = numRows;
int[][] twoDimArray = new int[numRows][numCols];
Random randGen = new Random();
for (int i = 0; i < numRows; i++) {
for (int j = 0; j < numCols; j++) {
int randIndex = randGen.nextInt(4);
int value = randGen.nextInt(100);
twoDimArray[i][j] = value;
}
}
System.out.println("\nThe two-dimensional array: ");
for (int i = 0; i < numRows; i++) {
for (int j = 0; j < numCols; j++) {
System.out.print(twoDimArray[i][j] + " ");
}
System.out.println();
}
}
}
I want to find a local minimum using a "brute force" approach. I know with a one dimensional array I would use a for-loop to compare all the elements in the array until I found a local minimum, but I don't know how to do that here.
Edit: Could I use binary search instead? Find the middle row and search there and if one isn't found, I search one of the halves.
The brute force method would be very similar to that of a 1D array, just with an extra loop, and a few more checks:
public int[] findLocalMinimum(int[][] arr) {
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr[i].length; j++) {
int current = arr[i][j];
if (i + 1 < arr.length && current >= arr[i + 1][j] ||
i - 1 >= 0 && current >= arr[i - 1][j] ||
j + 1 < arr[i].length && current >= arr[i][j + 1] ||
j - 1 >= 0 && current >= arr[i][j - 1]) {
continue;
} else {
return new int[] { i, j };
}
}
}
return new int[] { -1, -1 };
}
public static int[] uniqueRandomElements (int size) {
int[] a = new int[size];
for (int i = 0; i < size; i++) {
a[i] = (int)(Math.random()*10);
for (int j = 0; j < i; j++) {
if (a[i] == a[j]) {
a[j] = (int)(Math.random()*10);
}
}
}
for (int i = 0; i < a.length; i++) {
System.out.print(a[i]+" ");
}
System.out.println();
return a;
}
I have a method above which should generate an array of random elements that the user specifies. The randomly generated integers should be between 0 and 10 inclusive. I am able to generate random integers but the problem I have is checking for uniqueness. My attempt to check for uniqueness is in my code above but the array still contains duplicates of integers. What am I doing wrong and could someone give me a hint?
for (int i = 0; i < size; i++) {
a[i] = (int)(Math.random()*10);
for (int j = 0; j < i; j++) {
if (a[i] == a[j]) {
a[j] = (int)(Math.random()*10); //What's this! Another random number!
}
}
}
You do find the duplicate values. However, you replace it with another random number that may be a duplicate. Instead, try this:
for (int i = 0; i < size; i++) {
a[i] = (int)(Math.random()*10);//note, this generates numbers from [0,9]
for (int j = 0; j < i; j++) {
if (a[i] == a[j]) {
i--; //if a[i] is a duplicate of a[j], then run the outer loop on i again
break;
}
}
}
However, this method is inefficient. I recommend making a list of numbers, then randomizing it:
ArrayList<Integer> a = new ArrayList<>(11);
for (int i = 0; i <= 10; i++){ //to generate from 0-10 inclusive.
//For 0-9 inclusive, remove the = on the <=
a.add(i);
}
Collections.shuffle(a);
a = a.sublist(0,4);
//turn into array
Or you could do this:
ArrayList<Integer> list = new ArrayList<>(11);
for (int i = 0; i <= 10; i++){
list.add(i);
}
int[] a = new int[size];
for (int count = 0; count < size; count++){
a[count] = list.remove((int)(Math.random() * list.size()));
}
It might work out faster to start with a sequential array and shuffle it. Then they will all be unique by definition.
Take a look at Random shuffling of an array, and at the Collections.shuffle function.
int [] arr = [1,2,3,.....(size)]; //this is pseudo code
Collections.shuffle(arr);// you probably need to convert it to list first
If you have a duplicate you only regenerate the corresponding number once. But it might create another duplicate. You duplicate checking code should be enclosed in a loop:
while (true) {
boolean need_to_break = true;
for (int j = 0; j < i; j++) {
if (a[i] == a[j]) {
need_to_break = false; // we might get another conflict
a[j] = (int)(Math.random()*10);
}
}
if (need_to_break) break;
}
But make sure that size is less than 10, otherwise you will get an infinite loop.
Edit: while the above method solves the problem, it is not efficient and should not be used for large sized arrays. Also, this doesn't have a guaranteed upper bound on the number of iterations needed to finish.
A better solution (which unfortunately only solves second point) might be to generate a sequence of the distinct numbers you want to generate (the 10 numbers), randomly permute this sequence and then select only the first size elements of that sequence and copy them to your array. You'll trade some space for a guarantee on the time bounds.
int max_number = 10;
int[] all_numbers = new int[max_number];
for (int i = 0; i < max_number; i++)
all_numbers[i] = i;
/* randomly permute the sequence */
for (int i = max_number - 1; i >= 0; i--) {
int j = (int)(Math.random() * i); /* pick a random number up to i */
/* interchange the last element with the picked-up index */
int tmp = all_numbers[j];
all_numbers[j] = a[i];
all_numbers[i] = tmp;
}
/* get the a array */
for (int i = 0; i < size; i++)
a[i] = all_numbers[i];
Or, you can create an ArrayList with the same numbers and instead of the middle loop you can call Collections.shuffle() on it. Then you'd still need the third loop to get elements into a.
If you just don't want to pay for the added overhead to ArrayList, you can just use an array and use Knuth shuffle:
public Integer[] generateUnsortedIntegerArray(int numElements){
// Generate an array of integers
Integer[] randomInts = new Integer[numElements];
for(int i = 0; i < numElements; ++i){
randomInts[i] = i;
}
// Do the Knuth shuffle
for(int i = 0; i < numElements; ++i){
int randomIndex = (int)Math.floor(Math.random() * (i + 1));
Integer temp = randomInts[i];
randomInts[i] = randomInts[randomIndex];
randomInts[randomIndex] = temp;
}
return randomInts;
}
The above code produces numElements consecutive integers, without duplication in a uniformly random shuffled order.
import java.util.Scanner;
class Unique
{
public static void main(String[]args)
{
int i,j;
Scanner in=new Scanner(System.in);
int[] a=new int[10];
System.out.println("Here's a unique no.!!!!!!");
for(i=0;i<10;i++)
{
a[i]=(int)(Math.random()*10);
for(j=0;j<i;j++)
{
if(a[i]==a[j])
{
i--;
}
}
}
for(i=0;i<10;i++)
{
System.out.print(a[i]);
}
}
}
Input your size and get list of random unique numbers using Collections.
public static ArrayList<Integer> noRepeatShuffleList(int size) {
ArrayList<Integer> arr = new ArrayList<>();
for (int i = 0; i < size; i++) {
arr.add(i);
}
Collections.shuffle(arr);
return arr;
}
Elaborating Karthik's answer.
int[] a = new int[20];
for (int i = 0; i < size; i++) {
a[i] = (int) (Math.random() * 20);
for (int j = 0; j < i; j++) {
if (a[i] == a[j]) {
a[i] = (int) (Math.random() * 20); //What's this! Another random number!
i--;
break;
}
}
}
int[] a = new int [size];
for (int i = 0; i < size; i++)
{
a[i] = (int)(Math.random()*16); //numbers from 0-15
for (int j = 0; j < i; j++)
{
//Instead of the if, while verifies that all the elements are different with the help of j=0
while (a[i] == a[j])
{
a[i] = (int)(Math.random()*16); //numbers from 0-15
j=0;
}
}
}
for (int i = 0; i < a.length; i++)
{
System.out.println(i + ". " + a[i]);
}
//Initialize array with 9 elements
int [] myArr = new int [9];
//Creating new ArrayList of size 9
//and fill it with number from 1 to 9
ArrayList<Integer> myArrayList = new ArrayList<>(9);
for (int i = 0; i < 9; i++) {
myArrayList.add(i + 1);
}
//Using Collections, I shuffle my arrayList
Collections.shuffle(myArrayList);
//With for loop and method get() of ArrayList
//I fill my array
for(int i = 0; i < myArrayList.size(); i++){
myArr[i] = myArrayList.get(i);
}
//printing out my array
for(int i = 0; i < myArr.length; i++){
System.out.print(myArr[i] + " ");
}
You can try this solution:
public static int[] uniqueRandomElements(int size) {
List<Integer> numbers = IntStream.rangeClosed(0, size).boxed().collect(Collectors.toList());
return Collections.shuffle(numbers);
}
this algorithm is need to make an array with size X and then each number which isnt prime toput zero in his index.. can someone please tell me what is the complexity? and why?
// x is the number we want all the primes below him
int[] p = new int[x + 1];
// Initializes the array.
for (int i = 2; i < p.length; i++) {
p[i] = i;
}
// "Erases" the composite (non-prime) numbers.
for (int i = 2; i <= Math.sqrt(x); i++) {
for (int j = i * 2; j < p.length; j += i) {
p[j] = 0;
}
}
is the complexity is O(x*sqrt(x))?
If you are using the following code, the time complexity is O(x √x).
int[] p = new int[x];
for (int i = 0; i < p.length; i++) {
p[i] = i+1;
}
for (int i = 4; i <= p.length; i++) {
for(int j = 2; j <= Math.sqrt(i) ; j += 1) {
if(i%j==0) {
p[i-1] = 0;
}
}
}
I've been battling with this for some time and seem to be getting nowhere. The set up is so; I have a 2D array. For this array I need to iterate through each value and return the diagonal neighbours (5 values). These neighbours will be put into a new 1D [5] array and bubblesorted. The middle value (median) will then be returned and put into a new array of medians.
So far I have methods for extracting the diagonal neighbours:
//get diagonals from original DEM
double [] getDiagonals(int i, int j) {
double [] tempArray = new double [5];
tempArray[0] = data[i -1][j +1];
tempArray[1] = data[i -1][j -1];
tempArray[2] = data[i][j];
tempArray[3] = data[i +1][j -1];
tempArray[4] = data[i +1][j +1];
return tempArray;
}
I've then used this method in an iteration to get diagonals for each value in the original array:
//get diagonals for each
double [] [] bubbles(){
double [] [] datap = new double [298] [298];
for (int i = 1; i < data.length; i++){
for (int j = 1; j < data[i].length; j++) {
if ((i > 0) && (j > 0)) {
if ((i < data.length-1) && (j < data.length-1)){
double [] tempArray = getDiagonals(i, j);
//do something with the tempArray
I think this is where I'm coming unstuck. Through testing the getDiagonals method works fine. I'm struggling to get the tempArray out of the bubbles() method. If I set the output to be the tempArray it only returns the 5 values calculated for the bottom right corner of the original array.
I've tried calling other methods into the bubbles() method in order to do all the processing there and return a new array:
//get diagonals for each
double [] [] bubbles(){
double [] [] datap = new double [298] [298];
for (int i = 1; i < data.length; i++){
for (int j = 1; j < data[i].length; j++) {
if ((i > 0) && (j > 0)) {
if ((i < data.length-1) && (j < data.length-1)){
double [] tempArray = getDiagonals(i, j);
double sorted [] = sort(tempArray);
double median = sorted[2];
for (int z = 0; z < datap.length; z++){
for (int y = 0; y < datap[z].length; y++){
datap[z][y] = median;
}
}
}
}
}
}
return datap;
}
Again this fails and the output datap is just zeros. The sort() method above passed out the diagonals to a bubble sort method (which I know works on its
I guess my question is how to process within a method that is iterating and populate a new array?
I hope this makes sense but if you need more details please let me know. And yes, the sort I'm using is a bubble sort. I know they are rubbish but this is for a course I'm doing so it has to be used. And yes, I'm pretty new to java.
Any help would be greatly appreciated (and I'll even reference you if I need to use some code you provide ;)
The main issue that I see, is that with each traversal through your inner loop of:
for (int i = 1; i < data.length; i++){
for (int j = 1; j < data[i].length; j++) {
Where you call:
double [] tempArray = getDiagonals(i, j);
You are resetting all of the values of datap to be the current calculated median. To fix, you would need some way to indicate only the indices of the particular datap value that you want to populate.
You need to replace this section of your code:
for (int z = 0; z < datap.length; z++){
for (int y = 0; y < datap[z].length; y++){
datap[z][y] = median;
}
}
You could declare int y, z at the top of the method and do something like this:
if (y < datap.length){
if (z == datap.length[y] - 1){
y++;
z = 0;
}
datap[y][z] = median;
z++;
}
That way you are only assigning to the specific index in datap that you are trying to reach, instead of resetting each of its values.
Finally cracked it. To populate the whole array the following code works a peach.
//Diagonal to 1dArray and sorting
double [] [] bubbles()
{
double [][] tempArray = new double [300][300];
int y = 0;
int z = 0;
double median = 0;
for (int i = 0; i < data.length; i++)
{
for (int j = 0; j < data[i].length; j++)
{
if ((i > 0) && (j > 0))
{
if ((i +1 < data[i].length) && (j +1 < data[j].length))
{
double [] diagonals = getDiagonals(i, j);
//Need to sort here
median = diagonals[2];
tempArray[i][j] = median;
}
}
}
}
return tempArray;
}
The sorting was taken out and I haven't tested with it back in yet; but so far this is providing new values for all the cells in the temp array.