I'm sorry to bother, I just started trying to learn to code by my own.
I set myself a task to practice my basics. I'm supposed to generate random ints to populate an Array size 10, after that I have to sort it, look for the min, max and average value of all of the ints in the array and tell if the number 25 is in the array.
As you can see, the idea is to practice array manipulation and I'm not supposed to use built in functions.
So far I've written a method for assigning the random numbers to the array and another one to sort it (bubble sort, since is what I'm trying to learn).
Unfortunately I'm not able to sort the array by calling my sorting method (mySort) if I write the sorting algorithm myself.
If I use the built-in function for sorting inside my sorting method and then call it, it works perfectly. So I guess that means my algorithm is wrong.
I hope you guys could guide me and illuminate me as to what I'm doing wrong.
public static int randomNum;
public static void main(String args[]) {
generateRandomNumber(myArray);
mySort(myArray);
System.out.println(Arrays.toString(myArray));
}
private static int[] generateRandomNumber(int[] myArray) {
Random numberGenerator = new Random(Integer.MAX_VALUE);
for (int i = 0; i < myArray.length; i++) {
randomNum = numberGenerator.nextInt(100);
myArray[i] = randomNum;
}
return myArray;
}
private static void mySort(int[] myArray) {
for (int i = 0; i < myArray.length -1; i++) {
for (int j = 1; j < myArray.length- i -1; i++) {
if (myArray[j] < myArray[j - 1]) {
int temp = myArray[j - 1];
myArray[j - 1] = myArray[j];
myArray[j] = temp;
}
}
}
}
}
if I change to this:
private static void mySort(int[] myArray) {
Arrays.sort(myArray);
}
}
it works perfectly
There are several errors in your sorting code. The corrected version looks like this:
private static void mySort(int[] myArray) {
for (int i = 0; i < myArray.length; i++) { // Removed -1
for (int j = 1; j < myArray.length - i; j++) { // Removed -1, corrected from i++ to j++
if (myArray[j] < myArray[j - 1]) {
int temp = myArray[j - 1];
myArray[j - 1] = myArray[j];
myArray[j] = temp;
}
}
}
}
The -1 is not required since you use less than (<) in your loop condition. That means i or j will never exceed array size - 1.
Your code will work by making following changes to mySort function:
private static void mySort(int[] myArray) {
for (int i = 0; i <= myArray.length -1; i++) {// <= instead of <
for (int j = 1; j <= myArray.length- i -1; j++) {//j++ not i++ and do not miss =;
if (myArray[j] < myArray[j - 1]) {
int temp = myArray[j - 1];
myArray[j - 1] = myArray[j];
myArray[j] = temp;
}
}
}
}
In the inner loop, you are iterating over i instead of j. Fix it and it will work.
This is one of those annoying little pains in the ... code, which will haunt you
Start by taking a very, very close look at ....
for (int i = 0; i < myArray.length -1; i++) {
for (int j = 1; j < myArray.length- i -1; i++) {
Can't see it? Look more closely at the second line...
for (int j = 1; j < myArray.length- i -1; i++) {
j is always 1 ... but why? Because you increment i in both loops 😱
If you change the to something more like...
for (int i = 0; i < myArray.length -1; i++) {
for (int j = 1; j < myArray.length- i -1; j++) {
you should find it fixes the issue
Related
Code below is for pattern a, feel like once I get a I could get the others.
I like the array[int].length syntax in Java and was helpful to get the pattern to print as shown in the picture. But I do not think such a thing exists in C#.
class Main {
public static void main(String[] args)
{
char[][] arr = new char[10][10];
int starCount = 10;
for(int i = 0; i < arr.length; i++)
{
for(int j = 0; j < starCount; j++)
{
arr[i][j] = '*';
}
for(int k = starCount; k < arr[i].length; k++)
{
arr[i][k] = '-';
}
starCount--;
}
for(int a = 0; a < arr.length; a++)
{
for(int b = 0; b < arr[a].length; b++)
{
System.out.print(arr[a][b]);
}
System.out.println();
}
}
}
This code prints the * in a decreasing fashion but I am struggling with how to replace the empty elements of the array with the - character as shown in the image.
class MainClass {
public static void Main (string[] args)
{
char[ , ] arr = new char[10,10];
int starCount = 10;
for(int i = 0; i < arr.Length; i++)
{
for (int j = 0; j < starCount; j++)
{
arr[i , j] = '*';
}
for (int k = 0; ) //IDK WHAT TO DO TO ASSIGN ARR[I , K] = '-';
starCount--;
}
for (int i = 0; i < 10; i++)
{
for (int j = 0; j < 10; j++)
{
Console.Write(arr[i , j]);
}
Console.WriteLine();
}
}
}
You can use two nested for loops and one if else statement to print all of these patterns. This is Java code, but I think it can be easily converted to C#:
int n = 5;
for (int i = -n; i <= n; i++) {
for (int j = -n; j <= n; j++) {
// a) if (i + j <= 0)
// b) if (i + j >= 0)
// c) if (i <= j)
// d) if (Math.abs(i) + Math.abs(j) <= n)
if (i + j <= 0)
System.out.print("*");
else
System.out.print("-");
}
System.out.println();
}
Output (combined):
a) b) c) d)
*********** ----------* *********** -----*-----
**********- ---------** -********** ----***----
*********-- --------*** --********* ---*****---
********--- -------**** ---******** --*******--
*******---- ------***** ----******* -*********-
******----- -----****** -----****** ***********
*****------ ----******* ------***** -*********-
****------- ---******** -------**** --*******--
***-------- --********* --------*** ---*****---
**--------- -********** ---------** ----***----
*---------- *********** ----------* -----*-----
See also: Output an ASCII diamond shape using loops
Here's a different approach to the original problem, which might be easier for you to convert.
Build a string of 10 stars and 9 dashes, e.g. hard-coded that would be:
String line = "**********---------";
Now print a 10 rows with substrings of that string:
for (int i = 0; i < 10; i++)
System.out.println(line.substring(i, i + 10));
Output
**********
*********-
********--
*******---
******----
*****-----
****------
***-------
**--------
*---------
If the size is dynamic, based on an int value in variable starCount, then in Java 11+ you can use the repeat() method:
String line = "*".repeat(starCount) + "-".repeat(starCount - 1);
for (int i = 0; i < starCount; i++)
System.out.println(line.substring(i, i + starCount));
That one should be easy to do in C#. See: Best way to repeat a character in C#.
In versions of Java below 11, you can build a char[]:
char[] line = new char[2 * starCount - 1];
Arrays.fill(line, 0, starCount, '*');
Arrays.fill(line, starCount, line.length, '-');
for (int i = 0; i < starCount; i++)
System.out.println(new String(line, i, starCount));
The easiest way would be to look at the C# documentation for the Array class. There you would find that the Array class has a GetLength() method, that returns what the length property of a Java array returns.
Using that method you can change your code to
class MainClass {
public static void Main (string[] args)
{
char[ , ] arr = new char[10,10];
int starCount = 10;
for(int i = 0; i < arr.GetLength(0); i++)
{
for (int j = 0; j < starCount; j++)
{
arr[i , j] = '*';
}
for (int k = starCount; k < arr.GetLength(1); k++)
{
arr[i , k] = '*';
}
starCount--;
}
for (int i = 0; i < arr.GetLength(0); i++)
{
for (int j = 0; j < arr.GetLength(1); j++)
{
Console.Write(arr[i , j]);
}
Console.WriteLine();
}
}
}
For some reason when you switched from java to C# you went from using jagged arrays:
//java
char[][] arr = new char[10][10];
To rectangular arrays:
//c#
char[ , ] arr = new char[10,10];
This undoubtedly makes your life more hard work because it means a lot more has to change. C# supports jagged arrays in exactly the same way Java does, and in fact if I hadn't written "//java" above you wouldn't have been able to tell whether it was C# or java because they're the same
I like the array[int].length syntax in Java ... But I do not think such a thing exists in C#.
It absolutely does, and you need to change just one single character to get it: properties in C# are named in Pascal case, so you want Length, not length
In fact, the logic of that entire block of java you have will work just fine in C# - just paste it in and change the following minor changes:
length -> Length
System.out.print -> Console.Write
System.out.println -> Console.WriteLine
So I made this sortion sort method, all using for loops.
I revised it on white board over and over, it looks perfect, however, when I implemented it, it keeps giving me wrong sort, but if I reversed the if condition, it will give me the right answer but in reverse, this doesn't make sense!
public void insertionSort(){
for (int i = 1; i < items.length; i++){
for (int j = 0; j < i; j++){
if (items[i] < items[j]) {
int temp = items[i];
shift(items,j, i-1);
items[j] = temp;
}
}
}
}
private void shift(int[] array, int index1, int index2){
if (index1 == index2)
array[index1 + 1] = array[index1];
else{
for (int i = index2; i >= index1; i--)
array[i+1] = array[i];
}
}
Thanks for the input, I discovered the problem in my Array class, it simply doubles the array size, my mistake was that I used the array.length instead of count.
public void insertionSort(){
for (int i = 1; i < count; i++){
for (int j = 0; j < i; j++){
if (items[i] < items[j]) {
int temp = items[i];
shift(items,j, i-1);
items[j] = temp;
}
}
}
}
The problem is to count how many times my bubble sort algorithm switches the places of numbers. I tried to use a variable which increments by one each time, but I think there may be an error with scopes or something similar. Instead of returning a number such as 6 (which means numbers were swapped 6 times), it returns 0, which is what I initialized my variable as. How would I get my program to work?
public static int sort(int arr[]) {
int length = arr.length;
int temp;
int count = 0;
for (int i = 0; i < (length); i++) {
for (int j = 1; j < (length); j++) {
if (arr[j - 1] > arr[j]) {
temp = arr[j-1];
arr[j-1] = arr[j];
arr[j] = temp;
count++;
}
}
}
return count;
}
Looks like your algorithm is not optimized because of your for loop condition and initialization. As a result you are comparing an element with itself which is redundant.
Proper approach should be like below:
int yourCounter = 0;
for (int i = 0; i < length; i++)
for (int j = 1; j < length-i; j++)
if (arr[j - 1] > arr[j]) {
//swap code
//yourCounter++;
}
your counter should give you proper result then.
I was reading up on sorting algorithms, I finished selection and bubble sort and thought I should try to implement what I understood.It took me while to understand what I wrote intending to be selection sort(code snippet-1) wasn't implementing key features of selection sort at all(which is finding min of unsorted array and building sorted array one element at a time). So I wrote one more for selection sort(code snippet-3). But now, I'm curious about Snippet-1. Can someone tell me if it is bubble sort or not?
Code Snippet-1
public void sort(int[] arr) {
// code snippet-1
int n = arr.length;
for (int i = 0; i < n; i++) {
for(int j = i + 1; j < n; j++) {
if(arr[i] > arr[j]){
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
}
Code Snippet-2
public void sort(int[] arr) {
// code snippet-2
int n = arr.length;
for (int i = 0; i < n-1; i++) {
for (int j = 0; j < n-1; j++) {
if(arr[j] > arr[j+1]){
int temp=arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
}
}
Code Snippet-3
public void sort(int[] arr) {
// Code snippet-3
int n = arr.length;
for (int i = 0; i < n; i++) {
int min = i;
for(int j = i + 1; j < n; j++){
if(arr[j] < arr[min]) {
min = j;
}
}
int temp = arr[i];
arr[i] = arr[min];
arr[min] = temp;
}
}
Also, on a not so related account, can someone explain how the outer for loop condition (i.e i<n and i<n-1) doesn't affect the result in these cases? I only changed snippet-2's condition to j<n-1 as it gave me Arrayoutofbound error because of arr[j+1] term. Yes, I saw the entire thing in debug mode and animations too but still not completely clear how to choose a condition. I know I'm missing something here.
You have different approaches to bubble sort and the Arrayoutofbound exception is because of the comparison of n+1 element which is not there in the array.
In code snippet 2, you could also avoid one more loop by doing:
for (int i = 0; i <= n-2; i++)
I am stuck with an exercise which tells me to create a reversed array from the given one.
After some thinking I made such code:
public int[] reverse3(int[] nums) {
int[] nums2 = new int[3];
for (int i = nums.length - 1; i >= 0; i--) {
for (int j = 0; j < nums.length; j++) {
nums2[j] = nums[i];
}
}
return nums2;
}
But it is throwing out three exact same numbers.
You don't need a nested for loop - just iterate over the source array and fill the result array in the opposite order:
public int[] reverse(int[] nums) {
int len = nums.length;
int[] result = new int[len];
for (int i = 0; i < len; ++i) {
result[len - i - 1] = nums[i];
}
}
From a first look, your code should be more like this:
public int[] reverse3(int[] nums)
{
// initialize a second array with the same length
int[] nums2 = new int[nums.length];
// initialize the nums2 index
int index = 0;
// you only need one loop for this (since we'll be incrementing the index of nums2)
for (int i = nums.length - 1; i >= 0; i--) {
nums2[index] = nums[i];
index++;
}
return nums2;
}
Swap the symetric values in the array like this :
public static void reverse(int[] nums) {
for (int i = 0; i < nums.length / 2; i++) {
int temp = nums[i];
nums[i] = nums[nums.length - 1 - i];
nums[nums.length - 1 - i] = temp;
}
To reverse an array you only have to swap the elements until the midpoint:
public int[] reverse(int[] nums) {
int numsLength = nums.length;
for (int i = 0; i < numsLength / 2; i++) {
int temp = nums[i];
nums[i] = nums[numsLength - i - 1];
nums[numsLength - i - 1] = temp;
}
return nums;
}
This way is much more optimized.
Source: How do I reverse an int array in Java?
I am new to Java development and sorry if this question will be too
silly, but it seems like I am stuck with the exercise which tells me
to create a reversed array from the given one.
After some thinking I made such code:
public int[] reverse3(int[] nums) {
int[] nums2 = new int[3];
for (int i = nums.length - 1; i >= 0; i--) {
for (int j = 0; j < nums.length; j++) {
nums2[j] = nums[i];
} } return nums2; }
But it is throwing out three exact same numbers. Could I please count
on some help? Thank you
Use one loop only. If you want to use 2 arrays(wich i do not see the point.) this will work:
int j = 0;
for(int i = nums.length -1; i >= 0; i--){
nums2[j] = nums[i];
j++;
}
But if you want to use only one array, you can do this:
for (int i = 0; i < nums.length/2; i++) {
int aux = nums[i];
nums[i] = nums[nums.length-i-1];
nums[nums.length-i-1] = aux;
}
There are so many efficient ways to do it but to make you understand i am gonna modify your own code
public int[] reverse3(int[] nums) {
int[] nums2 = new int[3];
for (int i = nums.length - 1; i >= 0; i--) {
for (int j = (nums.length-1) - i; j < nums.length; j++) {
nums2[j] = nums[i];
}
}
return nums2;
}
or let's do a a little bit modification rather than using nums.length() again and again we can put it inside a variable
public int[] reverse3(int[] nums) {
int[] nums2 = new int[3];
int length = nums.length;
for (int i = length - 1; i >= 0; i--) {
for (int j = (length-1) - i; j < length; j++) {
nums2[j] = nums[i];
}
}
return nums2;
}
Remember it is not an efficient way but to make you understand i just modify the logic. Using nested loops like that will decrease the performance so better avoid it and try to do it in much more optimized way..