Bubble Sort and Project Euler Problem 1

As someone who is about to graduate and in the midst of interviewing for coding jobs I have found that I need to work on more problem solving skills in coding.  So I have decided to challenge myself and work on a few daily problems to enhance my skills a bit.

For student coders that aren’t aware there is a great website that helps you to develop your problem solving abilities called Project Euler (if you haven’t done problem one yet and don’t want to know the answer then stop reading this now).  It is a great site to develop skills and track them against your peers.

So here is the solution to problem 1:

Scanner reader = new Scanner(System.in);
System.out.println(“What number would you like to determine the sums of all the multiples of 3 or 5?”);
int n = reader.nextInt();

int factorOfThree = 0;
int factorOfFive = 0;
int sum = 0;

Array[] number = new Array[n];

for (int i = 0; i < number.length; i ++)
{
if (i % 3 == 0 || i % 5 == 0)
{
if (i % 3 == 0)
{
factorOfThree = i + factorOfThree;
}
else
{
factorOfFive = i + factorOfFive;
}
}

}

sum = factorOfThree + factorOfFive;

System.out.println(sum);

The solution is not perfect but I left my original answer here to show to students that your first solution is likely not the finished one.

I also figured out how to do a BubbleSort.  You can do this with a do-while loop as well but I am more comfortable with the for loop and that’s how I made it work for me.

int[] sortedArray = new int [10];
Random randomGenerator = new Random();

for (int idx = 1; idx <= 10; ++idx)
{
for (int i = 0; i < sortedArray.length; i ++)
{
int randomInt = randomGenerator.nextInt(100);
sortedArray[i] = randomInt;
}

}
System.out.println(Arrays.toString(sortedArray));

int n = sortedArray.length;
int temp = 0;
for (int k =0; k < n; k++ ){
for (int j = 1; j < n; j++){
//do {
if (sortedArray[j-1] > sortedArray[j]){
temp = sortedArray [j-1];
sortedArray [j-1] = sortedArray[j];
sortedArray [j] = temp;
}
}
}
System.out.println(Arrays.toString(sortedArray));

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s