How to read vector in java - java

I have used "combinatoricslib" to Generate combination from a object array. But the result is displayed as a vector. I want to know how to read only one value.
Here is the code.
// Create the initial vector
ICombinatoricsVector<String> initialVector = Factory.createVector(
new String[] { "red", "black", "white", "green", "blue" } );
// Create a simple combination generator to generate 3-combinations of the initial vector
Generator<String> gen = Factory.createSimpleCombinationGenerator(initialVector, 3);
// Print all possible combinations
for (ICombinatoricsVector<String> combination : gen) {
System.out.println(combination);
}
This is the result.
CombinatoricsVector=([red, black, white], size=3)
CombinatoricsVector=([red, black, green], size=3)
CombinatoricsVector=([red, black, blue], size=3)
CombinatoricsVector=([red, white, green], size=3)
CombinatoricsVector=([red, white, blue], size=3)
CombinatoricsVector=([red, green, blue], size=3)
CombinatoricsVector=([black, white, green], size=3)
CombinatoricsVector=([black, white, blue], size=3)
CombinatoricsVector=([black, green, blue], size=3)
CombinatoricsVector=([white, green, blue], size=3)
But it has both combination array and size. But i want to get only the array. how to get it.
Please help me. I am new to java.
Thanks in advance.

You simply need to read the javadoc. It took me 5 seconds to google it and find it: http://combinatoricslib.googlecode.com/svn/tags/release21/doc/org/paukov/combinatorics/ICombinatoricsVector.html
java.util.List<T> getVector()
Returns vector as a list of elements

I understand that what you're using here is an instance of combinatorics.CombinatoricsVector
It has a getVector method, which returns a List of all the elements in a vector like this (in this case, all the colours) and a getValue(int index) method, which allows you to retrieve an object at a specific index.

You can try this:
Generator<String> gen = Factory.createSimpleCombinationGenerator(initialVector, 3);
// Print all possible combinations
for (ICombinatoricsVector<String> combination : gen) {
System.out.println(combination.getValue(0)); // This gets the first value from the vector
System.out.println(combination.iterator().next()); // This is another way to do it
}
Check the Javadoc for details.

Perhaps this will work well for you:
// Print all possible combinations
for (ICombinatoricsVector<String> combination : gen) {
System.out.println(Arrays.toString(combination.toArray()));
}

Related

Changing brightness/saturation of a color in java

Currently I am working on a simulation project using javax.swing and I want to draw "grass" on my map based on it's food value. My food value is a double between 0 < 1, and I want to make it brighter as it gets bigger. I have been reading about HSB/HSV but cannot figure out how it works / the syntax of it. What is a good solution to this problem? Or can someone direct me somewhere that has a good tutorial?
class Grass{
private void setColor(){
grassColor = new Color(107, 142, 35); //RGB value I want to start with as "dead grass"
}
public Color getColor(){
return grassColor; //this is what i want to change based on food value;
}
private double growthRate = 0.1;
public void grow(){
foodValue += (foodValue < 1.0) ? growthRate : 0; //grows the grass to max size of 1.0
}
I guess I should also mention my food value is set to a random float when it initializes. Appreciate any advice.
private void setColor(){
grassColor = new Color(107, 142, 35);
}
See those numbers used to create your custom colour? They can be variable names pointing to numbers which get updated elsewhere based on whatever else in your program is supposed to influence the colour.
I sometimes refer to https://www.google.com/search?client=safari&rls=en&q=rgb+color+picker&ie=UTF-8&oe=UTF-8 to pick a suitable colour for the occasion. It neatly shows the values for different systems, not just RGB.
https://docs.oracle.com/javase/7/docs/api/java/awt/Color.html#getHSBColor(float,%20float,%20float) will give you a way to use HSB inputs if you don't want to go with the RGB system. There may be some other useful stuff there if you want to try yet another colour system.
You are probably best using the HSB colour model.
H = Hue; represents the colour circle:
Red, Yellow, Green, Cyan, Blue, Magenta, and back to Red.
S = Saturation; how pure the colour is:
Zero saturation is always a shade of grey. (R,G,B values are all equal)
Maximum saturation always has at least one of RGB value equal to zero.
B = Brightness; how dark the colour is:
Zero brightness is always Black
Using java.​awt.​Color.getHSBColor(h, s, b) you might start at (0.166, 0.8, 0.5)
which would be (yellow, slightly muted, medium dark), that is brownish,
then progress to (0.333, 1.0, 1.0) for a pure spring green
and perhaps end up with (0.4, 1.0, 0.9) for that darker, slightly bluer, summer result.
Play with the numbers to suit your needs.
You could bind your "green" value of your color directly to your foodValue. This will increase the green intensity of your color according to your foodValue. This would require no additional changes.
Example:
class Grass {
private double foodValue = 0.0;
private double growthRate = 0.1;
private Color grassColor;
public Grass() {
setColor();
}
private void setColor(){ // this could be removed if grassColor is initialized on top
grassColor = new Color(107, 142 + (int)(foodValue * 100), 35);
}
public Color getColor(){
return grassColor;
}
public void grow(){
foodValue += (foodValue < 1.0) ? growthRate : 0; //grows the grass to max size of 1.0
}
}
This is really simple and may work for your purposes.

Adding Colors to a Color array

I am writing a program where I take an image determine the average red channel, green channel and blue channel present in that image. I take these averages and pass them as parameters to a new color. I then want to add this color to an array. I repeat this process 24 times. The problem I face is that when I get a new color and add it to the array the previous colors get erased. I want to preserve the existing colors in the array and add to the one that hasn't been filled yet. Here is what I have tried.
System.out.println("R: "+ rAvg);
System.out.println("G: "+ gAvg);
System.out.println("B: "+ bAvg);
Color newColor = new Color(rAvg, gAvg, bAvg);
Color[] ColorArr = new Color[24];
for(int i = 0; i < ColorArr.length; i++){
ColorArr[i] = newColor;
}
System.out.println(Arrays.toString(ColorArr));
Here is the output after one color is added to the array
R: 206
G: 0
B: 0
[java.awt.Color[r=206,g=0,b=0],java.awt.Color[r=206,g=0,b=0]
Here is the array after I add a new color.
R: 211
G: 178
B: 230
[java.awt.Color[r=211,g=178,b=230], java.awt.Color[r=211,g=178,b=230]
The last color gets overwritten and replaced with the new color instead of going in the next index and preserving the last. How can I fix this so I preserve the entered colors in the array and place the new color the index after the previous?
You can restructure your code to something like this:
private Color[] colorArray = new Color[24];
private int currentIndex = 0;
public void addColorToArray(int red, int green, int blue) {
colorArray[currentIndex++] = new Color(red, green, blue);
}
public void myMethodThatDoThis24Times() {
addColorToArray(getRedAverage(), getGreenAverage(), getBlueAverage());
addColorToArray(getRedAverage(), getGreenAverage(), getBlueAverage());
...
}
Your logic looks correct. The only thing which you need to take care is creating a new instance of color object every time.
//ColorArr[i] = newColor; // Instead of this
ColorArr[i] = new Color(rAvg, gAvg, bAvg); // Do this for each element in array
You were initially doing Color newColor = new Color(rAvg, gAvg, bAvg); and assign the same newColor instance to all the elements in the ColorArr.
Thus, a single change in the newColor instance was reflecting the change in all its referenced elements in the array.
As #user alayor, rightly suggested to create new instances of Color(rAvg, gAvg, bAvg) with different RGB values.

Even distribution of colours

It's a pretty basic question however I can't understand it very well I'm afraid.
What I'm trying to do is spawn squares a certain colour out of 3 colours. each colour has it's own number value (-1, 0, 1) what I will then do is add that to a 2D array making a grid of squares.
For blue, it's a 1/4 chance. For red it's a 1/4 chance. For white it's a 1/2 chance.
I understand how to use Java's Random class, however I'm not quite sure how to implement what I'm looking for.
Could someone point me in the right direction?
Create a (1D) array the size of the number of squares, put the proportionate number of each colour into the array, random sort it (Collections.shuffle), and then pop them all off and into your 2D array.
Could someone point me in the right direction?
Create a square 2D array of int's: int[][] matrix = new int[SIZE][SIZE]
Fill it using random numbers from 0 to 3
CORRESPONDENCES (for example)
0-1 yellow
2 blue
3 red
Iterate over the 2D array and in each iteration:
draw a rectangle
increase y value (position) in each inner iteration and x in outer
assign color depending the value of the array.
HOW? Executing something like this method each iteration
//this will draw a square of size 50 at position x,y colored
public void paint(Graphics g, int color){
switch (color) {
case 2:
g.setColor(Color.blue);
break;
case 3:
g.setColor(Color.red);
break;
default:
g.setColor(Color.yellow);
break;
}
g.drawRect(x,y,50,50);
}
That's it, I think you have enough to achieve your goal.

Combine elements from ArrayLists

I know that some answers have been provided for similar questions, but none of them seemed to be suitable for my issue. I'm making a program to generate images for Granny Squares, or squares that have different color rings on the inside.
The user is able to select how many rings there are, and therefore the number of colors necessary will change. Therefore, I cannot use nested for loops to go through each color as the number of for loops would have to change. Is there a way I can create combinations for these colors?
For example, if I used the colors White, Blue, and Green, the following combinations would be White, White, White; White, White, Blue; White, White, Green; White, Blue, White; etc. So is there a way to accomplish this without nested for loops?
Here is an algorithm that achieves this using recursion.
public static void combine(List<Character> colors, List<Character> combination) {
if (combination.size() == colors.size()) {
System.out.println(combination);
} else {
for (char color : colors) {
combination.add(color);
combine(colors, combination);
combination.remove(combination.size() - 1);
}
}
}
public static void main(String[] args) {
List<Character> colors = new ArrayList<>();
colors.add('W');
colors.add('B');
colors.add('G');
combine(colors, new LinkedList<Character>());
}
colors is the original list of colors (W, B, G)
combinations is a list that is continually modified throughout the recursion to hold the current combination.
Here is what happens to combination until it first hits the base case
[W] // add W, call recursively
[W, W] // add W, call recursively
[W, W, W] // add W, call recursively
The base case is now met, and it prints [W, W, W]. It then removes the last color we put in the list, W, and adds the next color in colors to combination, which gives [W, W, B]. The base case is met again so it prints it out.
It continues to do this until all combinations have been printed.

String array in java random

String [] rnum = {"Black", "Red", "Black", "Red", "Black", "Red", "Black","Red",
"Black", "Red", "Black", "Red", "Black", "Red", "Black", "Red","Black", "Red", "Green"};
int A = rnum.length;
//the "Math.random() method will get you a random color
int random = (int) (Math.random() * A);
//randomize the strings
String Color = rnum[random];
How do i say "if color = black then do this" or same for green or same for red"
You mean...
if(Color.equals("Black")) {
// then do this
} else if(Color.equals("Red"){
// then do this
}
or even (In Java >= 1.7)
switch(Color) {
case "Black":
// then do this
break;
case "Red":
// then do this
break;
}
Color should not be capitalized, since that can be a Java class name.
For this purpose you can use a ternary operator (shortened if-else):
String color = ( rnum[random].compareTo("Black") == 0 ? ** do something here ** : ** do something if the color is not "Black" ** );
or:
String color = "";
if(rnum[random].compareTo("Black") == 0) {
// do stuff
}
else {
// it's not black. do other stuff.
}
With red and green, just replace "Black" with "Red", or "Green".
Using java equals method for each color is the simplest way.
http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#equals%28java.lang.Object%29
Others said the method to decide equality, I would add up something about the algorithm.
Consider adding weight of colours, I see Red and Black appear 9 times while Green appears once. I would add an object containing the name of the colour and the weight you want to apply. Like {"Green", 1}, {"Red", 9}, {"Black", 9}.
Sum up the weights and order the colours in some way and decide where the random number fell.
It would make more clean code and nicer solution.

Categories