I am developing a steganography program for a computer programming class. It appears to gives random ascii symbols. The output is supposed to be BINARY. The encode message method was given to us by my teacher. We just have to program the decode part.
import java.awt.*;
class HideMessage {
public void encodeMessage(Picture stegoObject, int[] binaryArray) {
Pixel pixelTarget = new Pixel(stegoObject, 0, 0);
Pixel[] pixelArray = stegoObject.getPixels();
Color pixelColor = null;
int redValue = 0;
for (int x = 0; x < binaryArray.length; x++) {
redValue = binaryArray[x];
pixelTarget = pixelArray[x];
pixelTarget.setRed(redValue);
}
pixelTarget = pixelArray[binaryArray.length];
pixelTarget.setRed(255);
System.out.println("FinishedPic");
stegoObject.write("SecretMessage.bmp");
stegoObject.explore();
}
public void decodeMessage(Picture decodepic) {
int redValue = 0;
Pixel targetPixel = null;
Color pixelColor = null;
int sum = 0;
for (int x = 0; redValue < 2; x++) {
//inside nested loop to traverse the image from left to right
for (int count = 1; count < 9; count++) {
targetPixel =
decodepic.getPixel(count + (8 * x), 0);
//gets the x,y coordinate of the target pixel
pixelColor = targetPixel.getColor();
//gets the color of the target pixel
redValue = pixelColor.getRed();
if (redValue == 1) {
if (count == 1) {
sum = sum + 128;
}
if (count == 2) {
sum = sum + 64;
}
if (count == 3) {
sum = sum + 32;
}
if (count == 4) {
sum = sum + 16;
}
if (count == 5) {
sum = sum + 8;
}
if (count == 6) {
sum = sum + 4;
}
if (count == 7) {
sum = sum + 2;
}
if (count == 8) {
sum = sum + 1;
}
}
System.out.println(sum);
}
System.out.println((char)sum);
sum = 0;
} //end of the inner for loop
}
}
public class HideMessageTester {
public static void main(String[] args) {
int[] bitArray =
{ 0, 1, 1, 0, 0, 0, 1, 0, 0, 1, 1, 0, 1, 0, 0, 1, 0, 1, 1,
0, 1, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 0, 1, 1, 1, 0, 0, 1, 0, 0,
1, 1, 1, 1, 0, 0, 1 };
//int[] bitArray =
{ 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 1, 0, 1, 0, 0, 1, 0, 1, 1,
0, 0, 1, 0, 0, 0, 1, 1, 0, 0, 1, 0, 0, 0, 1,
1, 0, 0, 1, 0, 1, 0, 1, 1, 0, 1, 1, 1, 0, 0,
0, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 0, 0, 1,
0, 1, 1, 0, 1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 0,
0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 1, 1,
0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 0, 1, 1, 0, 1,
0, 0, 1, 0, 1, 1, 0, 1, 1, 1, 0, 0, 0, 1, 0,
0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1,
0, 1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 1, 0, 1,
1, 0, 1, 0, 0, 0, 0, 1, 1, 1, 0, 1, 0, 0, 0,
0, 1, 0, 0, 0, 0, 1};
Picture stegoObject = new Picture("Earth.bmp");
HideMessage stego = new HideMessage();
stego.encodeMessage(stegoObject, bitArray);
Picture decodeObject = new Picture("SecretMessage.bmp");
System.out.println("Now Decoding");
stego.decodeMessage(decodeObject);
}
}
First, some general pieces of advice: I think your program is overly complicated because the functions are commingling their responsibilities:
Picture stegoObject = new Picture("Earth.bmp");
HideMessage stego = new HideMessage();
stego.encodeMessage(stegoObject, bitArray);
Picture decodeObject = new Picture("SecretMessage.bmp");
System.out.println("Now Decoding");
stego.decodeMessage(decodeObject);
I was very surprised to see SecretMessage.bmp; it wasn't at all obvious that were trying to decode the object you had just created. Sure, upon reading the encodeMessage() method it was easy enough to determine where it came from, but I think this flow would have been easier:
/* encode */
Picture pic_to_steg = new Picture("foo.bmp");
HideMessage stego = new HideMessage();
Picture secret = stego.encodeMessage(pic_to_steg, bitArray);
secret.write("SecretMessage.bmp");
/* decode */
Picture pic_with_message = new Picture("SecretMessage.bmp");
int[] hidden = stego.decodeMessage(pic_with_message);
/* output `hidden` and compare against `bitArray` */
In other words: leave the file IO entirely up to the main flow of the program. Perhaps your routines will be called from a network server in the future, and the pictures will never be saved to disk. That modification will be far easier if the routines operate on Pictures and return amended Pictures and int[].
Can you test your encodeMessage() method in isolation? Perhaps look at the differences in what it does between an input file and an output file. This section looks troublesome:
public void encodeMessage(Picture stegoObject, int[] binaryArray) {
Pixel pixelTarget = new Pixel(stegoObject, 0, 0);
Pixel[] pixelArray = stegoObject.getPixels();
Color pixelColor = null;
int redValue = 0;
for (int x = 0; x < binaryArray.length; x++) {
redValue = binaryArray[x];
pixelTarget = pixelArray[x];
pixelTarget.setRed(redValue);
}
pixelTarget = pixelArray[binaryArray.length];
pixelTarget.setRed(255);
Is the pixelArray really a reference into the image that can be updated through simple assignment? I'd really expect the design to look more like this pseudo-code:
pixel p = image.getPixel(x, y);
p.setred(binaryArray[i]);
image.setPixel(x, y, p);
The decoding has some strange loops:
for (int x = 0; redValue < 2; x++) {
//inside nested loop to traverse the image from left to right
for (int count = 1; count < 9; count++) {
This loop might work exactly as you designed it, but upon a first reading, it feels very wrong: You start with x=0, you increment x each time through the loop, but you use redValue < 2 as your loop termination rule.
I would so much rather see the loop written like this:
int x = 0;
while (redValue < 2) {
/* stuff */
x++;
}
(It isn't identical; x is still valid outside the loop, which can be dangerous. However, I think this is much more clear.)
There are cases where the termination clause of a for loop isn't related to the setup or increment clauses -- in my experience, they are very rare.
In this case though, it feels like a mistake; the condition redValue < 2 a loop invariant, but the inner loop assumes it will only happen on pixels that are multiples of 8, which is an assumption that is not enforced in the encodeMessage() method.
Trying to compute an integer value from your redValues as you read them is needlessly complicating your decode routine. I suggest removing the inner loop and return an array exactly like the array passed into the encodeMessage() routine. This will be (a) easier (b) easier to debug (c) easier to test (d) a thousand times easier to handle writing bit arrays that aren't evenly divisible by 8.
Then write a second method that turns the bit array output into the sum, or ASCII characters, or EBCDIC characters, or RSA key parameters, or whatever it is that's being encoded. Don't try to do too much at once. Writing a separate method to decode the array of bits will be (a) easier (b) easier to debug (c) easier to test (d) thousand time easier to handle arbitrary output modifications.
I hope these hints help.
Related
I have a method which finds the index of all the set bits in a binary string. It works fine except when the bits are set near the end. Here is the code.
public static void main(String[] args) throws InterruptedException {
indexSetBits(1101111100000000000000000000000000000000000000000000000000000000L);
}
public static ArrayList<Integer> indexSetBits(long bitboard) {
ArrayList<Integer> indices = new ArrayList<>();
int count = 0;
while (bitboard > 0L) {
if ((bitboard & 1L) == 1L) {
indices.add(count);
}
bitboard >>= 1;
count++;
}
return indices;
}
For some reason, when I pass in that 64 bit number as seen in my code, it gives the error: " Long number too large." Though i am sure what i am passing in is a 64 bit number. Is there any way to solve this?
Edit: It was pointed out that I was forgetting the "0b". Whoops!
Now that I remembered that, how would i make sure a method that returns a long, returns it in binary format, in other words how would i pass in a long without explicitly saying "0b".
For example I have this method which returns all the attack bits of a king as a long, and the logic with the bit mainuplation is fine within the actual method.
public long[] calculateKingMoves(int square, long ownSideBitboard,long enemySide, long allPieces){
/*
[0, 0, 0, 0, 0, 0, 0, 0]
[0, 0, 0, 0, 0, 0, 0, 0]
[0, 0, 0, 0, 0, 0, 0, 0]
[0, 0, 0, 1, 2, 3, 0, 0]
[0, 0, 0, 8, x, 4, 0, 0]
[0, 0, 0, 7, 6, 5, 0, 0]
[0, 0, 0, 0, 0, 0, 0, 0]
[0, 0, 0, 0, 0, 0, 0, 0]
*/
//8 possible moves for a king from a given position, unless on a border, under check, or attempting to move into a piece that is
// under the watch of another piece.
long kingBitBoard =1L<< square;
long kingAFile = kingBitBoard & Lookups.fileTables[0];
long kingHFile = kingBitBoard & Lookups.fileTables[Lookups.fileTables.length-2];
long move1 = kingAFile <<7;
long move2 = kingBitBoard <<8;
long move3 = kingHFile <<9;
long move4 = kingHFile <<1;
long move5 = kingHFile >> 7;
long move6 = kingBitBoard >>8;
long move7 = kingAFile >>9;
long move8 = kingAFile >>1;
long kingPsuedos = move1 | move2| move3| move4| move5| move6| move7| move8;
long kingMoves = kingPsuedos & ~allPieces;
long kingAttacks = kingPsuedos & enemySide;
return new long[]{kingMoves,kingAttacks};
}
How would i make sure the two longs returned were in binary format? Instead of just normal longs?
There are some similar threads and I have tried some solutions but none are working to how my result is intended to be.
I have a 2d array (Which is a game board).
If i want to move a playerID to a position in the board I want to check if that position has an adjacent cell that is equal to the player ID. Otherwise it wont place it.
For example if i have a board:
[0, 0, 0, 0, 0, 0, 0, 1, 0, 0]
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
[0, 0, 0, 0, 0, 0, 2, 0, 0, 0]
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
If i try 1 in position [0][0] it should reject it but if i try put it in either: [0][7], [0][9], [1][6], [1][7],[1][8] (this includes diagonals).
My current code was a starting attempt I guess? But im not sure how I could do the clientID check:
public void move(int client, int x, int y) {
int startPosX = (x - 1 < MIN_X) ? x : x-1;
int startPosY = (y - 1 < MIN_Y) ? y : y-1;
int endPosX = (x + 1 > MAX_X) ? x : x+1;
int endPosY = (y + 1 > MAX_Y) ? y : y+1;
for (int rowNum=startPosX; rowNum<=endPosX; rowNum++) {
for (int colNum=startPosY; colNum<=endPosY; colNum++) {
if (storeArray[x][y] == EMPTY && client <= 5 && client >= 1) {
storeArray[x][y] = client;
int count = totals.containsKey(client) ? totals.get(client) : 1;
totals.put(client, count + 1);
}
}
}
So it goes through the rows and columns and if it's in any of the surrounding cells, it should place it. But I can still place it anywhere.
Is my code even close to doing what it's supposed to do?
What sort of things am i missing to match my criteria and can this code be modified to make it work?
If you can't store the coordinates of clients you can modify your if statement to the following. If you can store the coordinates I would definitely use Leo Leontev's answer.
/*I removed check for client to be between 1-5, can be re-added.
I would add the checks for the desired spot being empty and the client
being within 1-5 to the top of the method.
For loop iterates over the possible spaces where the client would be in range
check if client is in a space*/
if (storeArray[rowNum][colNum]==client) {
//storeArray[rowNum][colNum]=0;
storeArray[x][y] = client;
//unchanged
int count = totals.containsKey(client) ? totals.get(client) : 1;
totals.put(client, count + 1);
}
You can also simplify your startX,Y, endX,Y by using Math.min and Math.max to avoid any indexOutOfBounds errors that may be caused by trying to move the client outside of the board.
int startPosX = Math.max(x-1,0);
int startPosY = Math.max(y-1,0;
int endPosX = Math.min(x+1,storeArray.length-1);
int endPosY = Math.min(y+1,storeArray[0].length-1);
If you're not doing anything after the totals.put(client,count+1); call you can add a return; statement to exit the method. If you still need to do more work you can add a label to the outer for loop and then break out of the label. Either way will stop your count from counting more than once per move.
outerloop:
for(int rowNum=startPosX;rowNum<=endPosX;rowNum++){
for(int colNum=startPosY;colNum<=endPosY;colNum++){
if(...){
//code
totals.put(client, count+1);
break outerloop;
}
}
}
Here is the method as it is in my editor
public static move(int client, int x, int y){
if(storeArray[x][y]==client)
return;
int startPosX = Math.max(x-1,0), startPosY=Math.max(y-1,0);
int endPosX = Math.min(x+1,storeArray.length-1), endPosY = Math.min(y+1,storeArray[0].length-1);
outerloop:
for(int rowNum=startPosX;rowNum<=endPosX;rowNum++)
{
for(int colNum=startPosY;colNum<=endPosY;colNum++){
if(storeArray[rowNum][colNum]==client)
{
storeArray[x][y]=client;
System.out.println("Successful move");
int count = totals.getOrDefault(client, 1);
totals.put(client, count + 1);
break outerloop;
//could set colNum=endPosY+1 and rowNum=endPosX+1 if you don't want to use label/break
}
}
}
}
You can use an array to store the coordinates of clients:
ArrayList<int[]> clientCoords = new ArrayList<>;
And so the move method will look like that:
public void move(int client, int x, int y) {
int[] coords = clientCoords.get(client);
int old_x = coords[0], old_y = coords[1]; // previous coordinates of the client
// check that the new cell is adjacent
if(Math.abs(x - old_x) <= 1 && Math.abs(y - old_y) <= 1){
clientCoords.set(client, new int[2]{x, y});
// your code
int count = totals.containsKey(client) ? totals.get(client) : 1;
totals.put(client, count + 1);
}
}
I'm making a project to go through a text file and output a tally of each letter in the file.
import java.util.*;
import java.io.*;
public class frequencyAnalysis {
private static String text;
public static String alphabet;
public static int Freq[];
public frequencyAnalysis(String text) {
this.text = text;
int [] Freq = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; //array of ints to keep track of how many of each letter there is.
alphabet = "abcdefghijklmnopqrstuvwxyz"; //point of reference for the program to know which number in the array should be increased
}
public static void freqAnalysis() throws IOException {
String token = "";
int index;
File subset = new File(text); //creates a new file from the text parameter
Scanner inFile = new Scanner(subset);
while(inFile.hasNext()) {
token = inFile.next();
index = alphabet.indexOf(token);
if (index == -1) { //makes sure that the character is a letter
break;
} else {
Freq[index]++;
}
}
inFile.close();
}
}
This is the class that's supposed to go through a given text file, and count how many of each letter there is in it.
import java.util.*;
import java.io.*;
public class tester {
public static void main(String args[]) throws IOException {
Scanner in = new Scanner(System.in);
System.out.println("Please type the input file path: "); //allows the user to specify a file
String input = in.next();
frequencyAnalysis Freq = new frequencyAnalysis(input);
frequencyAnalysis.freqAnalysis(); //calls the method to run through the file
for(int i = 0; i <= 25; i++){ //prints the alphabet and the Freq array
System.out.println(frequencyAnalysis.alphabet.charAt(i) + ": " + frequencyAnalysis.Freq[i]); //this is where the error is
}
}
}
This is the implementation class, which allows the user to specify a file and then runs the freqAnalysis method to adjust the static Freq array, which is then printed. However, when I run the program it gives me a java.lang.NullPointerException error on the specified line. I've already figured out that the problem is in "frequencyAnalysis.Freq[i]", not in "frequencyAnalysis.alphabet.charAt(i)". However, I don't know what the problem is or how to fix it.
In the constuctor you create an initialize local variable int [] Freq instead of class field.
Instead of:
int [] freq = {0, 0, 0, 0, 0, 0, ...
you should have:
freq = {0, 0, 0, 0, 0, 0, ...
Ok so you aren't initializing the array correctly in your frequencyAnalysis class.
public static int Freq[];
you think you're initializing it with
int [] Freq = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
but in reality it should be:
this.Freq = new int[]{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
The other answers are decent, but have some flaws in coding style.
First of all, integer arrays default to initialize with zeroes, so you can simplify your initialization of Freq. Also, you created a local variable Freq inside of your constructor for frequencyAnalysis instead of setting the static class variable.
You should change your constructor to this:
public frequencyAnalysis(String text) {
this.text = text;
frequencyAnalysis.Freq = new int[26]; //array of ints to keep track of how many of each letter there is.
alphabet = "abcdefghijklmnopqrstuvwxyz"; //point of reference for the program to know which number in the array should be increased
}
Also, class names should always be capitalized! (Change it to FrequencyAnalysis)
To let you know that is happening,
public frequencyAnalysis(String text) {
this.text = text;
int [] Freq = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; //array of ints to keep track of how many of each letter there is.
alphabet = "abcdefghijklmnopqrstuvwxyz"; //point of reference for the program to know which number in the array should be increased
}
When you do this int [] Freq is a new local variable the scope is limited to constructor and at the other side public static int Freq[]; is still Null, point to same variable for initialization, as stated above by others
I need to find the best fitting regression line for a set of points.
For example for this matrix:
int b [][] = { { 3, 1, 0, 0, 0, 0, 0, 0, 0 },
{ 1, 2, 3, 1, 0, 1, 0, 0, 0 },
{ 0, 1, 2, 1, 0, 0, 0, 0, 0 },
{ 0, 0, 0, 3, 0, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 0, 1, 3, 0, 0 },
{ 0, 0, 0, 0, 0, 1, 2, 3, 1 },
{ 0, 0, 0, 0, 0, 1, 1, 1, 2 },
{ 0, 0, 0, 0, 0, 0, 0, 0, 1 } };
Every number represents the amount of data points (weight I suppose) at that location (where rows are the X axis and Columns are for the Y).
I have attempted to use the SimpleRegression class from the apache mathematics library and am having some issues.
First, it doesn't appear to support weights. Second I believe that I'm doing something wrong, even for a matrix that is nothing but 1's on the main diagonal the slope/intercept results make no sense.
public static void main(String[] args) {
double a[][] = new double[9][9];
for (int i = 0; i < 9; i++)
a[i][i] = 1;
SimpleRegression r = new SimpleRegression(true);
r.addData(a);
System.out.println("Slope = " + r.getSlope());
System.out.println("Intercept = " + r.getIntercept());
}
This gives me results that are incorrect. I would assume that this matrix represents the function f(x) = x yet the slope I'm getting is -0.12499..
Could anyone point me at what I'm doing wrong?
I have a feeling I'm not only misusing the code but also the mathematics.
As the comments say, addData() expects a 2xN matrix of x y positions or individual x y positions. The following example returns a slope of 1 for a diagonal matrix as expected:
public static void main(String[] args) {
double a[][] = new double[9][9];
for (int i = 0; i < 9; i++)
a[i][i] = 1;
SimpleRegression r = new SimpleRegression(true);
addData(r, a);
System.out.println("Slope = " + r.getSlope());
System.out.println("Intercept = " + r.getIntercept());
}
public static void addData(SimpleRegression r, double[][] data) {
for(int x=0; x<data.length; x++) {
for(int y=0; y<data[0].length; y++) {
for(int i=0; i<data[x][y]; i++) {
r.addData(x, y);
}
}
}
}
The example assumes that index 0 corresponds to a position of 0, index 1 corresponds to a position of 1 and so on. If this is not the case you need to add a function to transform index to position.
I am attempting to iterate through a 2D array of integers to generate a tiled map using Java's Graphics2D.
int[][] mapArray = {{1, 1, 1, 1, 1, 1, 1, 1},
{1, 0, 0, 0, 0, 0, 0, 1},
{1, 0, 0, 0, 0, 0, 0, 1},
{1, 0, 0, 0, 0, 0, 0, 1},
{1, 0, 0, 0, 0, 0, 0, 1},
{1, 1, 1, 1, 1, 1, 1, 1}};
public void draw(Graphics2D g2d){
for(int y = 0; y < mapArray.length; y++){
for(int x = 0; x < mapArray[0].length; x++){
if(mapArray[x][y] == 1){
ImageIcon ic = new ImageIcon("/Textures/stone.jpg");
g2d.drawImage(ic.getImage(), x, y, null);
}
else if(mapArray[x][y] == 0){
ImageIcon ic = new ImageIcon("/Textures/water.jpg");
g2d.drawImage(ic.getImage(), x, y, null);
}
I just can't seem to wrap my head around the logic of iterating a 2D array. Ideally, each 0 would represent a water tile while each 1 would represent a stone tile. Every time I run this I get a NullPointerException.
x and y are wrong way around
public void draw(Graphics2D g2d){
for(int y = 0; y < mapArray.length; y++){
for(int x = 0; x < mapArray[y].length; x++){ //you want to use y here not 0
if(mapArray[y][x] == 1){ //first box is outer array second is inner one
ImageIcon ic = new ImageIcon("/Textures/stone.jpg");
g2d.drawImage(ic.getImage(), x, y, null);
} else if(mapArray[y][x] == 0){
ImageIcon ic = new ImageIcon("/Textures/water.jpg");
g2d.drawImage(ic.getImage(), x, y, null);
}
}
}
}
I could see potentially two big issues in your code, in your code "y" represents rows and "x" represents columns but in your if statement you are picking [column][row] and while having a dry run you are probabily counting [row][column] and secondly you are always counting columns that are present in first row. if your data structure is always nXn in such case it will work but in any other case you would have different results and you might encounter ArrayIndexOutofBound exception.