Information Warfare: Offense or Defense?

Information warfare is a big concern these days with the fast evolution of technology. Using information warfare offensively can provide an effective means of advancing foreign policy or persuade political agendas. Using information warfare in a defensive way can allow for protection of sensitive information that could potentially fall into the hands of a malicious person or government. They are just a few of the many ways that information can be used offensively or defensively in today’s world. Today we will cover some offensive uses of information warfare and some defensive uses of information warfare and why it is so important to stay ahead of your adversaries in the technological advances of information warfare.

When thinking about information warfare from an offensive standpoint, the United States has the most developed information infrastructure in the world. Using information warfare offensively in the United States could possibly be able to prevent actual physical weapons from being used in war preventing civilian deaths. On the other hand, if we used information warfare offensively we could potentially damage systems that control planes or nuclear power plants, which could potentially harm civilians. Another thing to consider while using information warfare offensively would be the case that offensively using information warfare is considered an act of war. If bombing a building or shooting down a plane is considered an act of war from one country to another, I think that shutting down a nuclear power plant and putting it in a state of meltdown could be considered an act of war. Therefore, the offensive end of information warfare can be a very complicated issue ethically and morally and as other countries information infrastructure becomes more advanced the department of defense will have to be very prepared and careful in the decision process.

From the defensive view of information warfare, of course, we have to be prepared. The United States is fully aware of the vulnerabilities of our information infrastructure and some say they fear the digital “Pearl Harbor”. Hopefully nothing extreme in the form of exploits of these vulnerabilities ever takes place. President Bush issued a national security directive 42 in 1990 recognizing the vulnerabilities and presidents thereafter have added to the directive. So the United States is prepared defensively for information warfare, as other countries become more information infrastructural sound. Being defensively prepared is the biggest concern because technology advances so quickly. Anyone can get his or her hands on malicious software, but the sensitive information is protected. Disabling access to malicious software for devious persons should be an action that the government should take.

source : https://fas.org/irp/eprint/snyder/infowarfare.htm

Weapons of Information Warfare

Information warfare is a very complex term because it can imply anything to do with any piece of information available in the world. If you think about it, there are libraries all over the world filled with information and how much information on the internet probable exceeds the amount in a library tremendously. The first weapon of Information warfare is information collection. Having information can be the turning point in any information usage scenario. Say that you bought a cabinet from the store and it did not come with instructions on how to put it together. Another person bought the same cabinet but theirs did come with instructions. You would figure that the person with the information on how to assemble the cabinet would get theirs assembled first. The same goes with information used in warfare, the ability to collect information will be advantageous to the person or entity planning to use that information.

Information transport is another weapon in information warfare. It is very useful to have a mode of transport for information. In the example above the person with the instruction to assemble the cabinet could surely assemble the cabinet faster, but what if that person left the instructions at their friends’ house. If that were the case then that person would assemble the cabinet just as fast as the person without the instructions, maybe even slower using time to find the instructions that are not available. Having a mode of transport for information that is collected is crucial in weaponizing information. Be it the internet, a network, even floppy disks, being able to get information from one place to another could be a deciding factor in using information in a war.

There is also the protection of the information used in information warfare. Any country in the world has their top-secret information that they cannot let any of their adversaries know about. Whether it be encryption or transport of information just through external drives cutting out the internet, the protection of information is crucial in information warfare. Think about an action movie where a person is transporting information in a briefcase that is handcuffed to their wrist. That is an excellent example of something that is really done with highly sensitive data for say a government contractor. Snowden leaked sensitive data, which is an example of a data breach that needs to be addressed. Those are just three of the weapons of the many used in information warfare. The world we live in will always come up with new information weapons to overcome their adversaries.

source : http://www.cs.cmu.edu/~burnsm/InfoWarfare.html

What is Information Warfare?

Information warfare has become the latest strategy in the never-ending war machine. It is using non-lethal attacks with information to disrupt their enemies’ information systems. The anatomy of information warfare is quite interesting as its main attacks are on electronic transmission, cyber attacks, and psychological operations. The Russians are notorious for the use of information warfare to cripple their neighboring countries. One way that information warfare is used to cripple electronic transmission systems is by jamming military communications or weapon guidance systems. This can have a very disastrous effect and the military should spare no expense in preventing such attacks. It can also target civilian uses like air traffic control, which prevents two planes from crashing into each other. Another example is to attack the Rail Traffic Management system which trains are fully controlled by.

Cyber attacks are a common place for information warfare also as disrupting computers for business can have a disastrous effect on a country. Say that the stock market was victim to a cyber attack rendering the stock market useless, which would put a big dent in the financial market. A socialist country could use that kind of an attack to try to cripple capitalism to push an agenda of some sort. I am sure that the government has many teams in place to work at preventing these types of cyber attacks. In the future maybe a mind reading apparatus that flies around in the sky marking areas where deception is taking place while alerting authorities who will sweep in and subdue the criminals could prevent a cyber attack. Another thing of great concern that a cyber attack could potentially target is a nuclear power plant. That could be catastrophic if the attack could trigger some sort of melt down and render a whole area of a country useless.

Lastly, there are the psychological operations that could degrade a nation’s morale by flooding social media with fake news. I read a substantial amount of fake news on social media and the President of the United States is always warning us about fake news. Psychological operations in information warfare are a big concern in today’s world. Being that the information on the internet is available to anyone in the world these days, I am sure that people would like to assure the validity of that information. Otherwise, the world will have misinformed people with malicious views due to misinformation, which could cripple a society.

source : https://www.weforum.org/agenda/2015/12/what-is-information-warfare

Information Warfare: Information Warriors

In 2016, President Obama created the Global Engagement Center to battle terrorist propaganda. The Global Engagement Center has also dealt with meddling from Russia in elections. The problem is fake news because in some countries they can make false news stories illegal but in America doing something like that would collide with the first amendment. President Trump is always talking about fake news and it is a real problem. The Global Engagement Center works with social media and FBI in an effort to prevent the spreading of foreign propaganda. They have to keep up with technology and their adversaries methods to prevent terrorist propaganda. Terrorist organizations used to use videos on social media to lure in potential recruits but now they have turned to advertisements and encrypted messaging applications. There is a never-ending amount of information that these information warriors in the global engagement center have to deal with.

Russian meddling in the election process is not a new thing. They have probably been doing it for decades with spies and a whole variety of platforms. The Russians have spread false information in Iraq and other Middle Eastern countries to try to persuade the people to be against the American soldiers that are stationed over there. There are a number of different strategies that information warriors can use against each other. Spreading fake news or false information seems to be a big part of what information warriors are doing. To prevent this kind of propaganda or threats from other countries in the future there would have to be a technological breakthrough that could actually read peoples’ minds or something of that sort. The future of information warfare is yet to be decided. With the technological breakthroughs, there are more warfare types and methods.

I have learned that there is a number of information warfare based institutions in the world and that multiple Presidents of the United States are trying to address the different, very complex issues with information warfare. Information Warriors being employed by the United States is a very in demand profession that needs to expand faster than the evolution of technology to be able to prevent the evolution of information warfare. Whether it is our allies or our adversaries, one of these days there will be a perfection of the use of information warfare and it will hopefully be the good people.

source : https://www.usatoday.com/story/news/world/2018/02/13/global-engagement-center-russia-meddling/333015002/

Information Warfare Mimetic Warfare

Memes are pieces of information within a culture that are passed around. I have studies memes in psychology and they are a very powerful tool especially when utilized for warfare. There are probably strategies in the department of defense to utilize memes. If you use any of the social networks these days you will see that they are jammed packed with memes. Many people do not know the significance of a meme or the power that one can have over a society or culture. Is the military working on a meme warfare division? The truth is after seeing the power of memes on society and cultures that they probably have many strategies that consist of using memes to persuade the people one way or the other.

One way to stay clear of the Mimetic Warfare is to use your common sense. Many memes out there should be considered jokes. However, some of society will be offended or more gullible to feed into the information that the meme represents. In one ear and out the other is the perfect strategy for viewing memes on the internet. By the time a meme may actually get to you, it could have been altered hundreds of different ways. There is really no credibility in memes if you think of them that way even though many of them are very funny. If a meme is a crack on an issue that is very important to you then you might feel offended or start to state your views and opinions more strongly over social media which could actually be a strategy of using memes in actual warfare.

Many people have much to say about memes but the majority of them do not take the time to sit back and think of the implications of some of the memes that they are spreading. Not everyone sees everything as a joke, even though I personally thing that memes are the best going brand of jokes out there. People need to lighten up and really start to appreciate the humorous qualities of memes instead of getting bitter when the implication of the meme touches a sensitive part of your views. Memes will always be used for a certain kind of information warfare and always have been. People have been complaining about memes since papers in print first came out a long time ago.

source : https://motherboard.vice.com/en_us/article/xyvwdk/meme-warfare

Politics and information warfare

Information warfare is no doubted a strategy that a weaker adversary would use to manipulate a stronger adversary. In the case of the politics in America, there is always the threat of Russian interference. There have been claims that Russia is using information warfare against the United States to interfere in the elections. Information warfare is a wide-open playing field consisting of anything to do with information. No one is safe from information warfare, you might think that a meme is funny when you read it, and it is, but that same meme could be a piece of information warfare targeted at a more gullible person. Information warfare is used heavily in social networks so being alert while reading things that are spreading around is very important.

Things with respect to the issue of social network manipulation with information warfare could evolve in a number of ways. One might someday see penalties for posting manipulating data on a social network site like community service. A policy to address this kind of issue is difficult to address because people are entitled to free speech and that is the main ingredient of information warfare. The public can get educated on this issue by following this one guideline, common sense. The far left and the far right of political parties are first in line to revolt on certain issues which makes great entertainment for the rest of us, but they lack common sense when it comes to social networking aspects. For example, lately there was a picture of President Trump coloring the American flag wrong. Now some people are saying that he does not even know what the flag looks like. However, the truth about that meme was that he was copying off the little girl next to him. It is not a big issue; it was just something funny that we can all appreciate the humor in.

My reaction to this news story was that it was interesting to read. It was an interview of a professor at a university who is suggesting that Russia meddling with the election is really a form of information warfare. He suggests that Russia floods social media with manipulating information leading to misinformed voters. I agree with him, there are many people misinformed about politics because of this kind of information warfare and like I said it all boils down to common sense.

source: https://www.npr.org/2018/07/21/631164914/meddling-vs-information-warfare

Information warfare the heartbreaker

The heartbreaker was an information warfare attack made against the Israeli military where Hamas hackers would set up profiles on social media and entice Israeli military personnel with sex. It started out with enticing them with sex, then the hackers would try to get the soldiers to download applications on their smart phones that were really spyware, and then they would use that spyware to extract sensitive data from the soldiers phones. When Google was informed of this spyware, they removed the applications from the store. This is interesting because now I know that some applications on the Google store could potentially be spyware for military operations. There are also so many hackers in Pakistan that they have made a law for preventing hacking. If a person is killed because of this hacking, the hacker is punished by execution.

I have learned that you cannot trust any old application on the market these days. A solution to not falling victim to spyware that is on the market is to wait a while until you download the app. If you wait a while before downloading the app there is a chance that Google or the app store will remove the app before you even decide to download it. Another thing that I learned is that there are some very skilled hackers in Pakistan. According to the article that I read Pakistan has one of the largest hacker communities in the world. If you are trying to make some hacking software, you might want to hire a pakistanian.

The evolution of this kind of information warfare can result in almost anything known to humankind. They were using social engineering and the solicitation of sex to lure Israeli soldiers into a trap. The future of that can be something like actually spoofing soldiers friends whole social network profiles and luring them in while the soldier thinks that it is their friend. To prevent this kind of attack the first thing to take into account is that you should never respond to the solicitation of sex. When someone is soliciting sex to you that is a red flag right there, unless you are in Las Vegas. Computer professionals have already addressed this kind of issue by figuring out about it and reporting it to Google and the app store in which the spyware apps have been removed.

source: http://www.strategypage.com/htmw/htiw/articles/20180721.aspx

QuickSort sorting algorithm in java with Generics that implement Comparable

In this article I’m going to touch on the sorting algorithm called Quicksort. Its worst case time complexity is O(n^2) and its best case time complexity is O(nlogn). Firstly the method we are going to make is going to take a generic array and those elements should implement the Comparable interface so they can be sorted. Take this Circle class for example. When you implement the Comparable interface you specify in the compareTomethod what makes a circle greater than, less than, or equal to another circle. In this example we return whether the radius of the circle is bigger or smaller than the circle it is being compared to.

Circle.java

/**
 * author: copypasteearth
 * date: 7/17/2019
 */
public class Circle implements Comparable<Circle> {
    public int xValue;
    public int yValue;
    public int radius;

@Override
public int compareTo(Circle o) {
return (this.radius - o.radius);
}
@Override
public String toString() {
return "x: " + xValue + " ---y: " + yValue + " ---radius: " + radius;
}
}

Next we create the Quicksort class that has the method quicksort and a main method to test out the quicksort method. The quicksort method is a recursive method and the base case is if(a < b). The method goes through the generic array and sorts the elements based on what the compareTo method tells it. Here is the Quicksort class.

Quicksort.java

/**
 * author: copypasteearth
 * date: 7/17/2019
 */
import java.util.Random;
public class QuickSort<T extends Comparable<T>> {

public static <T extends Comparable<T>> void quicksort(T[] array, int a, int b) {
if (a < b) {
int i = a, j = b;
T x = array[(i + j) / 2];

do {
while (array[i].compareTo(x) < 0) i++;
while (x.compareTo(array[j]) < 0) j--;

if ( i <= j) {
T tmp = array[i];
array[i] = array[j];
array[j] = tmp;
i++;
j--;
}

} while (i <= j);

quicksort(array, a, j);
quicksort(array, i, b);
}
}

public static void main(String[] args) {
Integer[] integerarray = {50, 55, 11, 89, 90, 1, 20, 11};
QuickSort<Integer> qsinteger = new QuickSort<Integer>();
qsinteger.quicksort(integerarray, 0, integerarray.length-1);
for(Integer i: integerarray) {
System.out.println(i);
}
String[] stringarray = {"bird","moth","apple","zebra","banana","desert","pig"};
QuickSort<String> qsstring = new QuickSort<String>();
qsstring.quicksort(stringarray, 0, stringarray.length-1);
for(String i: stringarray) {
System.out.println(i);
}
Circle[] circlearray = new Circle[20];
Random rand = new Random();
for (int index = 0; index < 20; index++)
{
circlearray[index] = new Circle();
circlearray[index].xValue = Math.abs(rand.nextInt()) % 100;
circlearray[index].yValue = Math.abs(rand.nextInt()) % 100;
circlearray[index].radius = Math.abs(rand.nextInt()) % 100;

}
System.out.println("Circle Array Unsorted....");
for(int i = 0;i < 20;i++){

System.out.println(circlearray[i]);
}
QuickSort<Circle> qscircle = new QuickSort<Circle>();
qscircle.quicksort(circlearray, 0, circlearray.length-1);
System.out.println("Circle Array Sorted");
for(Circle i: circlearray) {
System.out.println(i);
}

}

}

If you run this code you will see the results from the main method. First it sorts an Integer array and then a String array. Then it makes a Circle array and prints them out unsorted then it sorts them and then prints them out again sorted. That pretty much does it for this example on quicksorting. In the future I will probably go through the rest of the sorting algorithms. Hope you enjoyed it.

Donate or Subscribe to support Copypasteearth!!!!!


×
Your Donation
copypasteearth@gmail.com">

How to make a mouse maze in Java

This is the code to make a mouse maze with recursion using a stack and a list with a GUI in Java.

First we will make a Mouse class

Mouse.java

import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

public class Mouse {
public int x,y;
public Stack<Coordinate> decisions;
public List<Coordinate> solution;

public Mouse(int x, int y){
this.x = x;
this.y = y;
decisions = new Stack<Coordinate>();
solution = new ArrayList<Coordinate>();
}
}

Then we will make the coordinate class

Coordinate.java

public class Coordinate {
public int x,y;

public Coordinate(int x,int y){
this.x = x;
this.y = y;
}

@Override
public boolean equals(Object obj) {

boolean sameSame = false;
if (obj != null && obj instanceof Coordinate)
{
if(this.x == ((Coordinate)obj).x && this.y == ((Coordinate)obj).y){
sameSame = true;
}

}
return sameSame;
}
}

Now its time for the decision class

Decision.java

public class Decision {

public boolean up,down,left,right;
public int x,y;
public Decision(int x, int y){
up = down = left = right = false;
this.x = x;
this.y = y;
}
public Decision(boolean up,boolean down,boolean right,boolean left){
this.up = up;
this.down = down;
this.right = right;
this.left = left;
}
public void setLeft(boolean left){
this.left = left;
}
public void setRight(boolean right){
this.right = right;
}
public void setUp(boolean up){
this.up = up;
}
public void setDown(boolean down){
this.down = down;
}
@Override
public String toString() {
// TODO Auto-generated method stub
return x + " x -- y " + y;
}

}

Now we have to make the maze class which does most of the hard work

Maze.java

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;
import javax.swing.JComponent;

public class Maze extends JComponent{
public char[][] maze = null;
public Rectangle[][] rects = null;
public boolean mousebool = false;
public boolean backtrack = false;
public Mouse mouse;
public Random random = new Random();
public Coordinate startingPoint;
public boolean first = true;
public boolean solv = true;
public int lastx,lasty;
public String navigation = "working!!!";

@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);

if(maze != null){
for(int i = 0;i < maze.length;i++){
for(int j = 0;j < maze[0].length;j++){
if(maze[i][j] == '1'){
g.setColor(Color.BLACK);
g.fillRect(rects[i][j].x, rects[i][j].y, rects[i][j].width, rects[i][j].height);
g.setColor(Color.WHITE);
g.drawRect(rects[i][j].x, rects[i][j].y, rects[i][j].width, rects[i][j].height);
}else if(maze[i][j] == '0'){
g.setColor(Color.white);
g.fillRect(rects[i][j].x, rects[i][j].y, rects[i][j].width, rects[i][j].height);
g.setColor(Color.BLACK);
g.drawRect(rects[i][j].x, rects[i][j].y, rects[i][j].width, rects[i][j].height);
}
}
}
if(mousebool){
g.setColor(Color.PINK);

g.fillOval(rects[mouse.x][mouse.y].x, rects[mouse.x][mouse.y].y, rects[mouse.x][mouse.y].width, rects[mouse.x][mouse.y].height);
}
}

}
public void setMaze(char[][] maze){
mousebool = false;
this.maze = maze;
rects = new Rectangle[maze.length][maze[0].length];
for(int i = 0;i < rects.length;i++){
for(int j = 0;j < rects[0].length;j++){
rects[i][j] = new Rectangle(i * (getWidth()/rects.length),j * (getHeight()/rects[0].length)
,getWidth()/rects.length,getHeight()/rects[0].length);
}
}
repaint();
}
public void setMouse(int x,int y){
mousebool = true;
mouse = new Mouse(x,y);
startingPoint = new Coordinate(x,y);
mouse.solution.add(new Coordinate(x,y));
mouse.decisions.push(new Coordinate(x,y));
first = true;

repaint();
}
public void solve(){

if(mouse.x > 0 && mouse.x < maze.length - 1 && mouse.y > 0 && mouse.y < maze[0].length - 1 && mouse.decisions.size() > 0){

//System.out.println(wasHere(coord) + "now");
//north
System.out.println(wasHere(new Coordinate(mouse.x,mouse.y - 1)) + "north");
if (!(maze[mouse.x][mouse.y - 1] == '1') && !wasHere(new Coordinate(mouse.x,mouse.y - 1))) mouse.decisions.push(new Coordinate(mouse.x,mouse.y - 1));
//east
System.out.println(wasHere(new Coordinate(mouse.x + 1,mouse.y)) + "east");
if (!(maze[mouse.x + 1][mouse.y] == '1') && !wasHere(new Coordinate(mouse.x + 1,mouse.y))) mouse.decisions.push(new Coordinate(mouse.x + 1,mouse.y));
//west
if (!(maze[mouse.x - 1][mouse.y] == '1') && !wasHere(new Coordinate(mouse.x - 1,mouse.y))) mouse.decisions.push(new Coordinate(mouse.x - 1,mouse.y));
//south
if(!(maze[mouse.x][mouse.y + 1] == '1') && !wasHere(new Coordinate(mouse.x,mouse.y + 1))) mouse.decisions.push(new Coordinate(mouse.x,mouse.y + 1));

Coordinate coord = mouse.decisions.pop();

mouse.x = coord.x;
mouse.y = coord.y;

mouse.solution.add(coord);

ActionListener taskPerformer = new ActionListener() {

@Override
public void actionPerformed(ActionEvent arg0) {
solve();

}
};
javax.swing.Timer t = new javax.swing.Timer( 250, taskPerformer);
t.setRepeats(false);
t.start();
//solve();

repaint();
}else{
solv = false;
if(mouse.decisions.size() == 0){
mouse.solution.clear();
navigation = "there is no solution";
}else{
mouse.solution.clear();
findPath(startingPoint.x,startingPoint.y);
navigation = "maze complete";
}
}

//solve();
}
public boolean findPath(int x,int y){
if(x < 0 || y < 0 || x > maze.length - 1 || y > maze[0].length - 1)return false;

if(!(x > 0 && x < maze.length - 1 && y > 0 && y < maze[0].length - 1) && maze[x][y] == '0')
{
mouse.solution.add(new Coordinate(x,y));
return true;// && maze[x][y] == '0') return true;//&& maze[x][y] == '0') return true;
}
if(maze[x][y] == '1') return false;

mouse.solution.add(new Coordinate(x,y));
if(!mouse.solution.contains(new Coordinate(x,y - 1)))
if(findPath(x,y-1) == true) return true;
if(!mouse.solution.contains(new Coordinate(x+1,y)))
if(findPath(x + 1,y) == true) return true;
if(!mouse.solution.contains(new Coordinate(x,y+1)))
if(findPath(x,y + 1)== true) return true;
if(!mouse.solution.contains(new Coordinate(x-1,y)))
if(findPath(x - 1,y)== true) return true;
mouse.solution.remove(new Coordinate(x,y));
return false;
}

public boolean wasHere(Coordinate coord){
return mouse.solution.contains(coord);
}
public void TraverseMouse(int x){
if(x < mouse.solution.size()){
Coordinate coord = mouse.solution.get(x);
mouse.x = coord.x;
mouse.y = coord.y;
final int xt = x+=1;
ActionListener taskPerformer = new ActionListener() {

@Override
public void actionPerformed(ActionEvent arg0) {
TraverseMouse(xt);

}
};
javax.swing.Timer t = new javax.swing.Timer( 250, taskPerformer);
t.setRepeats(false);
t.start();
}
repaint();

}
public String Navigation(){
return navigation;
}
}

And finally the Main class to make the GUI

Main.java

import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.filechooser.FileNameExtensionFilter;

public class Main {
public static int width;
public static int height;
public static char[][] maze1;
public static void main(String[] args) {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
}catch(Exception ex) {
ex.printStackTrace();
}

SwingUtilities.invokeLater(new Runnable() {
public void run() {
create();
}
});

}
public static void create(){
JFrame frame = new JFrame("Mouse Maze");
final Maze maze = new Maze();
frame.setSize(500, 500);
frame.setLocation((int)(Toolkit.getDefaultToolkit().getScreenSize().getWidth()/2)-264,
(int)(Toolkit.getDefaultToolkit().getScreenSize().getHeight()/2)-330);
maze.setSize(400, 400);
Container content = frame.getContentPane();
//Creates a new container
content.setLayout(new BorderLayout());

frame.add(maze,BorderLayout.CENTER);
//frame.add(maze);
JPanel panel = new JPanel(new BorderLayout());
JPanel panel1 = new JPanel(new BorderLayout());
JPanel panel2 = new JPanel(new BorderLayout());
JPanel finish = new JPanel(new BorderLayout());
final JLabel textFile = new JLabel(" ex: maze.txt ");
JButton pickFile = new JButton("Pick file");
pickFile.addActionListener(new ActionListener(){

@Override
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
JFileChooser chooser = new JFileChooser();
FileNameExtensionFilter filter = new FileNameExtensionFilter(
".txt file", "txt");
chooser.setFileFilter(filter);

int returnVal = chooser.showOpenDialog(null);
if(returnVal == JFileChooser.APPROVE_OPTION) {
try {
BufferedReader read = new BufferedReader(new FileReader(chooser.getSelectedFile()));
String rea = read.readLine();
String[] split = rea.split(" ");
width = Integer.valueOf(split[0]);
height = Integer.valueOf(split[1]);

String readline;
int num = 0;
maze1 = new char[width][height];
while((readline = read.readLine()) != null){
char[] ch = readline.toCharArray();
for(int i = 0;i < ch.length;i++){
maze1[i][num] = ch[i];
}
num++;
}
maze.setMaze(maze1);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
textFile.setText(chooser.getSelectedFile().getName());
}else{

}
}

});

panel.add(pickFile,BorderLayout.CENTER);
panel.add(textFile,BorderLayout.WEST);
JButton setMouse = new JButton("Set Mouse");
final JTextField mouseText = new JTextField("x,y",15);
JButton solve = new JButton("SOLVE");
JButton traverse = new JButton("TRAVERSE");
final JLabel error = new JLabel("ERROR MESSAGES!!!!");
panel2.add(solve,BorderLayout.NORTH);
panel2.add(traverse,BorderLayout.CENTER);
panel2.add(error,BorderLayout.SOUTH);
panel1.add(setMouse,BorderLayout.CENTER);
panel1.add(mouseText,BorderLayout.WEST);
finish.add(panel,BorderLayout.NORTH);
finish.add(panel1,BorderLayout.CENTER);
finish.add(panel2,BorderLayout.SOUTH);
//content.setLayout(new BorderLayout());
content.add(finish, BorderLayout.SOUTH);
traverse.addActionListener(new ActionListener(){

@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
maze.TraverseMouse(0);
}

});
solve.addActionListener(new ActionListener(){

@Override
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub

maze.solve();

error.setText(maze.navigation);

}

});
setMouse.addActionListener(new ActionListener(){

@Override
public void actionPerformed(ActionEvent arg0) {
String mousePosition = mouseText.getText();
String[] splitposition = mousePosition.split(",");
try{
int x = Integer.valueOf(splitposition[0]);
int y = Integer.valueOf(splitposition[1]);
if(x >= width || y >= height){
error.setText("those coordinates are not in range of your maze, try again, 0-"+ (width - 1)+",0-"+(height-1));
}else if(maze1[x][y] == '1'){
error.setText("you cannot place the mouse on a wall, try again");
}else{
maze.setMouse(x, y);
error.setText("coordinates set.");
}
}catch(NumberFormatException e){
error.setText("You Must enter the mouse position \"x,y\" example: 10,20");
}catch(ArrayIndexOutOfBoundsException e){
e.printStackTrace();
error.setText("You Must enter the mouse position \"x,y\" example: 10,20");
}

}

});

//frame.add(panel);

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//makes it so you can close
frame.setVisible(true);
//char[][] ch = new char[][]{{'1','1','1','1'},{'1','0','0','1'},{'1','0','0','1'},{'1','1','1','1'}};
//maze.setMaze(ch);
}

}

You will have to use a text file in this format where a 1 is a wall and a 0 is part of the path remember .txt file the first line means 10 width and 5 height for the maze


10 5
1111111111
1010001111
1011011111
1011000011
1111111111

You can try it and alter it to your own code, thanks for reading.

Donate or Subscribe to support Copypasteearth!!!!!


×
Your Donation

How to Implement a Stack in Java

If you are a computer science major when you take Data Structures and Algorithms you are going to have to learn about a Stack.  Java has a built in Stack class that you can use so you would probably never have to implement your own. In this example we will start with the Stack interface to formally define how our stack will be implemented.

Stack.java


/**
*
* @author Copypasteearth
*interface for the Stack implementation
* @param <T>
* generic parameter T
*/
public interface Stack<T>
{
/*
* push element onto the top of the stack
* @element
* the item to be pushed onto the top of the stack
*
*/
public void push(T element);
/**
* removes the top element from the stack and returns it
* @throws
* throws stackunderflowexception if the stack is empty
* @return
* returns T element
*/
public T pop();
/**
* lets you see the current top element of the stack without removing it
* @throws
* throws stackunderflowexception if the stack is empty
* @return
* returns T element (the top of the stack)
*/
public T top();
/**
* checks to see if the stack is empty
* @return
* returns true if the stack is empty, false otherwise
*/
public boolean isEmpty();
/**
* gets the size of the stack
* @return
* returns an integer representing how many items are on the stack
*/
public int getSize();

}

Next we will need a class that holds our information so we define the Node class to hold the data and a reference to the next Node in the stack.

Node.java


/**
*
* @author Copypasteearth
* Node class used to dynamically keep track of
* elements on the stack
*/
public class Node<T> {

/** holds the reference to Object of the node*/
public T data;
/** holds the reference to next node of the stack*/
public Node<T> next;
/**
*
* @param element
* element to be placed in data variable of Node
* @param next
* Node to be placed in next variable of Node
*/
public Node(T element,Node<T> next) {

this.data = element;
this.next = next;

}

}

Now we will define an Exception just incase someone trys to access the top of the stack and it is empty.

StackUnderflowException.java


/**
*
* @author Copypasteearth
* StackUnderflowException to be thrown when the
* stack tries to perform a getter method on an empty stack
*/
public class StackUnderflowException extends RuntimeException {

public StackUnderflowException() {
super();
// TODO Auto-generated constructor stub
}

public StackUnderflowException(String arg0) {
super(arg0);
// TODO Auto-generated constructor stub
}

public StackUnderflowException(Throwable arg0) {
super(arg0);
// TODO Auto-generated constructor stub
}

public StackUnderflowException(String arg0, Throwable arg1) {
super(arg0, arg1);
// TODO Auto-generated constructor stub
}

public StackUnderflowException(String arg0, Throwable arg1, boolean arg2,
boolean arg3) {
super(arg0, arg1, arg2, arg3);
// TODO Auto-generated constructor stub
}

}

And finally here is the implementation of the Stack interface, in a class called UnboundedStackImplementation.

UnboundedStackImplementation.java


/**
* @author Copypasteearth
*
* UnboundedStackImplementation is the version of a Stack
* created with the Stack interface dynamically creating
* instances of Node class to keep references to elements
* in the stack
*/
public class UnboundedStackImplementation<T> implements Stack<T> {

/** the count of how many elements are in the stack */
private int count;
/** the reference to the element on the top of the stack */
private Node<T> top;

/**
* constructor sets values of top and count and returns an
* instance of UnboundedStackImplementation
*/
public UnboundedStackImplementation()
{
this.count = 0;
this.top = null;
}

/*
* push element onto the top of the stack
* @element
* the item to be pushed onto the top of the stack
*
*/
@Override
public void push(T element) {

//create new node with element as data and top as next
Node<T> currentNode = new Node<T>(element,top);
//set top to the new node
top = currentNode;
//increment count
count++;


}

/**
* removes the top element from the stack and returns it
* @throws
* throws stackunderflowexception if the stack is empty
* @return
* returns T element
*/
@Override
public T pop() {
//get T with top method, may throw StackUnderflowException
T result = top();
//set top data to null
top.data = null;
//set top to the top next node
top = top.next;
//decrement count
count--;
return result;

}

/**
* lets you see the current top element of the stack without removing it
* @throws
* throws stackunderflowexception if the stack is empty
* @return
* returns T element (the top of the stack)
*/
@Override
public T top() {

//prepare result T to be returned by top
T result = null;
// if stack is not empty
if(!isEmpty()){
//set result to top variable data
result = top.data;
}else{
// if stack is empty there is no data to be returned
throw new StackUnderflowException("StackUnderflowException -- The Stack is empty!!!");
}

return result;
}

/**
* checks to see if the stack is empty
* @return
* returns true if the stack is empty, false otherwise
*/
@Override
public boolean isEmpty() {
if(top == null)
return true;
else
return false;
}

/**
* gets the size of the stack
* @return
* returns an integer representing how many items are on the stack
*/
@Override
public int getSize() {

return count;
}

}

And that’s it, I hope you appreciate this little demonstration about the data structure that is very commonly used in practice.  There are a ton of different data structures to choose from and some are better in certain situations than others.

%d bloggers like this: