Making 2d Array Java - multidimensional-array

say I have a 1D array like
int[] array1d = {1,2,3}
I would like to convert it into 2D array2d[3][2] which holding 2 int that are different. E.g.:
1 2
1 3
2 3
currently I made this
int[] array1d = new int[3];
array1d[0] = 1;
array1d[1] = 2;
array1d[2] = 3;
int[][] array2d = new int[3][2];
for (int i=0; i<3; i++) {
for (int j=0; j<2; j++) {
array2d[i][j] = array1d[j];
}
}
but it gives me only 1,2.

Generally speaking, what you want is called combinations (in your example, of size 2 taken from a 3-sized array). So, order does not matter (e.g. [1, 2] equals [2, 1]).
As already specified in the comments, you should consider a more general solution and one can be found here. Besides the actual code, you will also find a code reviews from Codereview community.

i have done this using random numbers.try this code
` import java.util.Random;
public final class RandomInteger {
public static void main(String... aArgs){
Random randomGenerator = new Random();
int[] array1d = new int[3];
array1d[0] = 1;
array1d[1] = 2;
array1d[2] = 3;
int[] array2d = new int[3][2];
int randomInt;
for (int i=0; i<3; i++) {
for (int j=0; j<2; j++) {
randomInt = randomGenerator.nextInt(3);
array2d[i][j] = array1d[randomInt];
}
}
}
}
`

Related

How create an adjacency matrix of a Maze graph

I'm working on making a maze Generator using Prim's Algorithm. I understand i have to make an undirected weighted graph and represent it on an Adjacency Matrix or List. i created the boolean[][] adjacenyMatrix array to show which edges currently exist in the maze. But i have an issue trying to implement the algorithm i thought of. Here is my code:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner (System.in);
System.out.println("Please enter the size of the maze");
int mazeHeight = scanner.nextInt();
int mazeWidth = scanner.nextInt();
int noOfNodes = mazeHeight * mazeWidth;
boolean[][] adjacencyMatrix = new boolean[noOfNodes][noOfNodes];
for (int i = 0; i < mazeHeight; i++) {
for (int j = 0; j < mazeWidth; j++ ) {
// Edges exist from left to right
adjacencyMatrix[i][j] = true;
adjacencyMatrix[j][i] = true;
}
}
for (int i = 0; i < mazeWidth; i++) {
for (int j = 0; j < noOfNodes; j + mazeWidth) { // <-----------I'm having an issue here; Not a statement
// Edges exist from top to bottom
adjacencyMatrix[i][j] = true;
adjacencyMatrix[j][i] = true;
}
}
}
}
After taking a break; i looked over it and realised that i forgot to include the "=" symbol >.<
so j += mazeWidth

Beginner coder checking if input is part of a cycle?

public Graph (int nb){
this.nbNodes = nb;
this.adjacency = new boolean [nb][nb];
for (int i = 0; i < nb; i++){
for (int j = 0; j < nb; j++){
this.adjacency[i][j] = false;
}
}
}
public void addEdge (int i, int j){
if(!(i<0 || i>=this.nbNodes|| j<0 || j>=this.nbNodes))
{
this.adjacency[i][j] = true;
this.adjacency[j][i] = true;
}
}
public void removeEdge (int i, int j){
if(!(i<0 || i>=this.nbNodes|| j<0 || j>=this.nbNodes))
{
this.adjacency[i][j] = false;
this.adjacency[j][i] = false;
}
}
public int nbEdges(){
int c =0;
for(int i=0; i<this.nbNodes; i++)
{
for(int j= 0; j<this.nbNodes; j++)
{
if(this.adjacency[i][j]==true)
{
c++;
}
}
}
return c/2;
}
public boolean cycle(int start){
return false;
}
A Graph has a number of nodes nbNodes and is characterized by its adjacency matrix adjacency. adjacency[i][j] states whether or not there is an edge from the i-th node to the j-th node.
the graphs are undirected.
I am a beginner coder and am having trouble writing cycle(int start)
It takes as input an integer, g.cycle(i) returns true if the i-th node is part of a cycle (and false otherwise).
does anyone have any idea on how I should approach this?

MPI min function in reduce

I am trying to find the minimum number in my array of integers, however, it returns 0.
import mpi.*;
import java.util.Random;
class AddIntSR
{
public static void main(String[] params) throws Exception
{
MPI.Init(params);
int me = MPI.COMM_WORLD.Rank();
int size = MPI.COMM_WORLD.Size();
final int CHUNKSIZE = 1;
final int ROOT = 0;
Random rg = new Random();
int [] bigBuf = new int[CHUNKSIZE *size];
int [] smallBuf = new int[CHUNKSIZE];
int [] minBuf = new int[1];
int localTotal = 0;
if (me == ROOT)
{
for(int i = 0; i< bigBuf.length; i++)
bigBuf[i] = rg.nextInt(10);
for(int i = 0; i< bigBuf.length; i++)
System.out.println("bigBuf "+bigBuf[i]);
}
MPI.COMM_WORLD.Scatter(bigBuf,0,CHUNKSIZE,MPI.INT,smallBuf,0,CHUNKSIZE,MPI.INT,ROOT);
if(me!= ROOT)
{
System.out.println("smallBuf "+me+ ": "+smallBuf[0]);
for(int i = 0; i < smallBuf.length; i++)
localTotal += smallBuf[i];
}
MPI.COMM_WORLD.Reduce(new int[]{localTotal},0,bigBuf,0,1,MPI.INT,MPI.MAX,ROOT);
MPI.COMM_WORLD.Reduce(new int[]{localTotal},0,minBuf,0,1,MPI.INT,MPI.MIN,ROOT);
if(me == ROOT)
{
System.out.println(bigBuf[0]);
System.out.println(minBuf[0]);
}
}
}
I am not sure why it does not work. The maximum function seems to work fine.
Also, how would I be able to access the integer that is sent to processor 0 so it is included in the min/max comparison?
Thank you.
The MIN reduction always results in 0 since localTotal is always 0 in rank ROOT and this is indeed the minimum value.
After the MPI.COMM_WORLD.Scatter call, all process including ROOT will have a piece of data in their smallBuf. Therefore you should remove the following conditional, i.e.:
if(me!= ROOT)
{
System.out.println("smallBuf "+me+ ": "+smallBuf[0]);
for(int i = 0; i < smallBuf.length; i++)
localTotal += smallBuf[i];
}
should become simply:
System.out.println("smallBuf "+me+ ": "+smallBuf[0]);
for(int i = 0; i < smallBuf.length; i++)
localTotal += smallBuf[i];

Perlin Noise Assistance

Ok so I found this article and I am confused by some parts of it. If anyone can explain this process in more depth to me I would greatly appreciate it because I have been trying to code this for 2 months now and still have not gotten a correct version working yet. I am specifically confused about the Persistence part of the article because I mostly do not understand what the author is trying to explain about it and at the bottom of the article he talks about a 2D pseudo code implementation of this but the PerlinNoise_2D function does not make sense to me because after the random value is smoothed and interpolated, it is an integer value but the function takes float values? Underneath the persistence portion there is the octaves part. I do not quite understand because he "adds" the smoothed functions together to get the Perlin function. What does he mean by"adds" because you obviously do not add the values together. So if anyone can explain these parts to me I would be very happy. Thanks.
Here is my code:
import java.awt.Color;
import java.awt.Graphics;
import java.util.Random;
import javax.swing.JFrame;
import javax.swing.JPanel;
#SuppressWarnings("serial")
public class TerrainGen extends JPanel {
public static int layers = 3;
public static float[][][][] noise = new float[16][16][81][layers];
public static int[][][][] octaves = new int[16][16][81][layers];
public static int[][][][] perlin = new int[16][16][81][layers];
public static int[][][] perlinnoise = new int[16][16][81];
public static int SmoothAmount = 3;
public static int interpolate1 = 0;
public static int interpolate2 = 10;
public static double persistence = 0.25;
//generate noise
//smooth noise
//interpolate noise
//perlin equation
public TerrainGen() {
for(int t = 0; t < layers; t++) {
for(int z = 0; z < 81; z++) {
for(int y = 0; y < 16; y++) {
for(int x = 0; x < 16; x++) {
noise[x][y][z][t] = GenerateNoise();
}
}
}
}
for(int t = 0; t < layers; t++) {
SmoothNoise(t);
}
for(int t = 0; t < layers; t++) {
for(int z = 0; z < 81; z++) {
for(int y = 0; y < 16; y++) {
for(int x = 0; x < 16; x++) {
octaves[x][y][z][t] = InterpolateNoise(interpolate1, interpolate2, noise[x][y][z][t]);
}
}
}
}
for(int t = 0; t < layers; t++) {
PerlinNoise(t);
}
}
public static Random generation = new Random(5);
public float GenerateNoise() {
float i = generation.nextFloat();
return i;
}
public void SmoothNoise(int t) {
//Huge smoothing algorithm
}
//Cosine interpolation
public int InterpolateNoise(int base, int top, float input) {
return (int) ((1 - ((1 - Math.cos(input * 3.1415927)) * 0.5)) + top * ((1 - Math.cos(input * 3.1415927)) * 0.5));
}
public void PerlinNoise(int t) {
double f = Math.pow(2.0, new Double(t));
double a = Math.pow(persistence, new Double(t));
for(int z = 0; z < 81; z++) {
for(int y = 0; y < 16; y++) {
for(int x = 0; x < 16; x++) {
perlin[x][y][z][t] = (int) ((octaves[x][y][z][t] * f) * a);
}
}
}
}
public static void main(String [] args) {
JFrame frame = new JFrame();
frame.setSize(180, 180);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
TerrainGen test = new TerrainGen();
frame.add(test);
frame.setVisible(true);
}
public static int size = 5;
public void paintComponent(Graphics g) {
super.paintComponent(g);
int i = 0;
for(int t = 0; t < 9; t++) {
for(int z = 0; z < 9; z++) {
for(int y = 0; y < 16; y++) {
for(int x = 0; x < 16; x++) {
g.setColor(new Color(perlin[x][y][i][0] * 10, perlin[x][y][i][0] * 10, perlin[x][y][i][0] * 10));
g.fillRect((z * (16 * size)) + (x * size), (t * (16 * size)) + (y * size), size, size);
}
}
i++;
}
}
repaint();
}
}
And I did not include the smoothing part because that was about 400 lines of code to smooth between chunks.
What the article calls persistence is how the amplitude of the higher frequency noises "falls off" when they are combined.
"octaves" are just what the article calls the noise functions at different frequencies.
You take 1.0 and repeatedly multiply by the persistence to get the list of amplitudes to multiply each octave by - e.g. a persistence of 0.8 gives factors 1.0, 0.8, 0.64, 0.512.
The noise is not an integer, his function Noise1 produces noise in the range 0..1 - i.e. variable n is an Int32 bit it returns a float.
The input paramters are integers i.e. The Noise1 function is only evaluated at (1, 0) or (2, 2).
After smoothing/smearing the noise a bit in SmoothNoise_1 the values get interpolated to produce the values inbetween.
Hope that helped!!
this loop makes octaves from 2d noise. same loop would work for 3d perlin...
function octaves( vtx: Vector3 ): float
{
var total = 0.0;
for (var i:int = 1; i < 7; i ++)//num octaves
{
total+= PerlinNoise(Vector3 (vtx.x*(i*i),0.0,vtx.z*(i*i)))/(i*i);
}
return total;//added multiple perlins into noise with 1/2/4/8 etc ratios
}
the best thing i have seen for learning perlin is the following code. instead of hash tables, it uses sin based semi random function. using 2-3 octaves it becomes high quality perlin... the amazing thing is that i ran 30 octave of this on a realtime landscape and it didnt slow down, whereas i used 1 voronoi once and it was slowing. so... amazing code to learn from.
#ifndef __noise_hlsl_
#define __noise_hlsl_
// hash based 3d value noise
// function taken from https://www.shadertoy.com/view/XslGRr
// Created by inigo quilez - iq/2013
// License Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported License.
// ported from GLSL to HLSL
float hash( float n )
{
return frac(sin(n)*43758.5453);
}
float noise( float3 x )
{
// The noise function returns a value in the range -1.0f -> 1.0f
float3 p = floor(x);
float3 f = frac(x);
f = f*f*(3.0-2.0*f);
float n = p.x + p.y*57.0 + 113.0*p.z;
return lerp(lerp(lerp( hash(n+0.0), hash(n+1.0),f.x),
lerp( hash(n+57.0), hash(n+58.0),f.x),f.y),
lerp(lerp( hash(n+113.0), hash(n+114.0),f.x),
lerp( hash(n+170.0), hash(n+171.0),f.x),f.y),f.z);
}
note that sin is expensive on CPU, instead you would use:
function hash ( n: float ): float
{//random -1, 1
var e = ( n *73.9543)%1;
return (e*e*142.05432)%2-1;// fast cpu random by me :) uses e*e rather than sin
}

Get Positive Bits Indexes from Bit Array

Say I have the following BitArray combinedResults = searchBitArray.And(genreBitArray);
Which contains positive bits i.e 100100110000
How can I get the indexes of all the positive ones ?
Here's a first, decidedly ghetto, crack at it:
BitArray ba = new BitArray(new bool[] {true,false,false,true,false,false,true,true,false,false,false,false});
List<int> pos = new List<int>();
for (int i = 0; i < ba.Length; i++)
{
if (ba[i])
pos.Add(i);
}
That would give you a list containing 0, 3, 6, 7. You could start at ba.Length - 1 and decrement down to zero if you need to read from right to left.
edit: Wrapped in an extension method, just because:
void Main()
{
BitArray ba = new BitArray(new bool[] {true,false,false,true,false,false,true,true,false,false,false,false});
List<int> positives = ba.GetBitPositions(true);
List<int> negatives = ba.GetBitPositions(false);
}
public static class BitArrayExtensions
{
public static List<int> GetBitPositions(this BitArray ba, bool MatchCondition)
{
List<int> pos = new List<int>();
for (int i = 0; i < ba.Length; i++)
{
if (ba[i] == MatchCondition)
pos.Add(i);
}
return pos;
}
}

Resources