for loops and snippets where we reassign variables - java

The task is: write a program that swaps the maximum and minimum elements of a given array. Print the array before and after this operation.
I am still a huge noob at programming, most of the time I just can't really picture what the codes are doing.
public class problem6 {
public static void main(String[] args) {
int[] arr = new int[15];
for (int i = 0; i < arr.length; i++)
/*
I don't think I really understand incrementation in loops, what exactly do they do? As far as I understand
it is like having an industry line? I suppose 'i' would be the product and '++' would be the thing that
carries 'i' to the be checked one by one? I really need an ape analogy because I can't really visualize it.
*/
arr[i] = (int) (Math.random() * 15);
for (int i = 0; i < arr.length; i++)
System.out.print(arr[i] + ", ");
System.out.println();
int minIndex = 0, maxIndex = 0; //why do we assign min and max to 0 and not any other number?
for (int i = 1; i < arr.length; i++) {
if (arr[minIndex] > arr[i])
minIndex = i;
if (arr[maxIndex] < arr[i])
maxIndex = i;
/*
I see a lot of codes like:
if (arr[minIndex] > arr[i])
minIndex = i;
if (arr[maxIndex] < arr[i])
maxIndex = i;
what purpose does it serve? For the lack of knowledge and from a really noob programmer's perspective
it seems like we are "reassigning" minIndex and maxIndex to 'i', which is probably not what we're actually doing
but I don't know how to describe it other way.
*/
}
System.out.println(minIndex + " " + arr[minIndex]);
System.out.println(maxIndex + " " + arr[maxIndex]);
{
int tmp = arr[minIndex];
arr[minIndex] = arr[maxIndex];
arr[maxIndex] = tmp;
/*
Here again, for the lack of understanding and better way of describing, it seems to me that we are reassigning,
which makes it appear illogical to me, but I'd assume it's not actually "reassigning".
int tmp = arr[minIndex];
arr[minIndex] = arr[maxIndex];
arr[maxIndex] = tmp;
*/
}
for (int i = 0; i < arr.length; i++)
System.out.print(arr[i] + ", ");
System.out.println();
}
}

What is i, what does it do and what does i++ mean:
i is used in this loop to indicate how many times you've looped through said loop.
The ++ is there to do i + 1 after each time you've looped trough the for loop.
For better understanding on how you use i in your example, imagine the array arr being a big book and what you write in the [] is which page you want to open. In the loop you basically flip through the book to each pagenumber in those brackets.
Why does minIndex and maxIndex get set to 0 instead of any other number?
They get set to 0 because we can assume that that is the lowest possible Index in your array. So when the Index gets compared to any other possible number that could be the lowest or highest Index, it always gets set to said lowest or highest Index instead of always having the same value you set because no other value in your array is higher or lower than that.
Why do we make arr[minIndex] assert the same value as arr[maxIndex]?
In your question's title you said that you wanted to swap the highest number in your array with the lowest number. So now that we have found the highest and lowest number in your array these steps switch the two.
If you have any other questions or if any of my descriptions are unclear, just comment under the answer and I'll do my best to help you out. Also, don't look down on yourself so much. Everyone was a "noob" at some point :)

Here is quick fix for you.
Following is complete example of swaps the maximum and minimum elements of a given array.
Input :
Enter elements you want to input in array:
5
Enter all the elements:
10
15
16
1
9
Output :
Element After swaps :
10
15
1
16
9
public static void main(String arg[]) {
Scanner scan = null;
int number;
try {
scan = new Scanner(System.in);
System.out.println("Enter elements you want to input in array: ");
number = scan.nextInt();
int array[] = new int[number];
System.out.println("Enter all the elements:");
for (int i = 0; i < number; i++) {
array[i] = scan.nextInt();
}
int[] resultArray = swap(array);
System.out.println("Element After swaps :");
for (int i : resultArray) {
System.out.println(i);
}
} catch (Exception ex) {
ex.printStackTrace();
} finally {
scan.close();
}
}
public static int[] swap(int[] array) {
int minIndex = 0, maxIndex = 0;
for (int i = 1; i < array.length; ++i) {
if (array[i] < array[minIndex])
minIndex = i;
if (array[i] > array[maxIndex])
maxIndex = i;
}
int t;
if (maxIndex != minIndex) {
t = array[minIndex];
array[minIndex] = array[maxIndex];
array[maxIndex] = t;
}
return array;
}
Hope this solution works.
Please mark as answer if this solution is helpful.

Related

Index out of bounds for Length and not sorting correctly

I am working on a selection sort algorithm and I'm running into a problem. Sometimes it sorts correctly, sometimes it doesn't. And I constantly run into the error "Index _ out of bounds for length _"
I'm completely stumped. Any advice? Work done in Java
public class Selection{
System.out.println("Please input a value for N");
Scanner input = new Scanner(System.in);
int n = input.nextInt();
int[] array = new int[n];
for (int i =0; i < n; i++) {
System.out.println("Please input a value for index" + i);
int element = input.nextInt();
array[i] = element;
}
select(array);
}
public static void select(int[] sorter) {
for (int i = 0; i< sorter.length; i++) {
int k = sorter[i];
int lowest_number = sorter[i + 1];
for (int j = i; j < sorter.length; j++) {
if (sorter[j] > -1){
lowest_number = j;
}
}
int intermediate = sorter[i];
sorter[i] = sorter[lowest_number};
sorter[lowest_number] = intermediate;
System.out.println("----------");
printarray(sorter);
}
}
public static void printarray(int[] print) {
for (int i = 0; i < [rint.length; i++) {
System.out.println(print[i]);
}
}
}
Your IndexOutOfBoundsException is caused by this code:
int lowest_number = sorter[i + 1];
which gets index i + 1 from sorter, which is one too much in case that i is sorter.length - 1.
Another issue is that lowest_number is being set to the last non-negative value index in sorter, rather than to the lowest value index.
This should give you a good indication on what to work on without giving away a full working insertion sort algorithm right away, as practise seems to be the goal here.

Largest number in k swaps

Given a number K and string str of digits denoting a positive integer, build the largest number possible by performing swap operations on the digits of str at most K times.
Example 1:
Input:
K = 4
str = "1234567"
Output:
7654321
Explanation:
Three swaps can make the
input 1234567 to 7654321, swapping 1
with 7, 2 with 6 and finally 3 with 5
I am trying to solve it using two loops. For every index i, I am finding the largest integer between (i+1)th index to (N-1)th index, where N is the size of string. If the largest number is greater than arr[i], then swap it. Below is the code I have written.
public static String findMaximumNum(String str, int k) {
int N = str.length();
int[] arr = new int[N];
for (int i = 0; i < N; i++) {
arr[i] = Integer.valueOf(str.charAt(i) + "");
}
int swaps = 0;
for (int i = 0; i < N - 1; i++) {
if(swaps == k)
break;
int maxIndex = findMaxInRange(arr, i + 1, N - 1);
if (arr[i] < arr[maxIndex]) {
swap(arr, i, maxIndex);
swaps++;
}
}
String out = "";
for (int i = 0; i < N; i++) {
out = out + arr[i] + "";
}
return out;
}
private static int findMaxInRange(int[] arr, int i, int j) {
int max = Integer.MIN_VALUE;
int maxIndex = i;
for (int k = i; k <= j; k++) {
if (arr[k] >= max) {
max = arr[k];
maxIndex = k;
}
}
return maxIndex;
}
private static void swap(int[] arr, int i, int j) {
System.out.println("swapping "+arr[i]+" and "+arr[j]+" from "+Arrays.toString(arr));
int ch = arr[i];
arr[i] = arr[j];
arr[j] = ch;
}
public static void main(String[] args) {
System.out.println(findMaximumNum("61892795431", 4));
}
It is failing for few test cases. One of the test cases where it is failing is
Input:
4
61892795431
Its Correct output is:
99876215431
And MyCode's output is:
99876125431
I am not able to figure out how the output is '99876215431' and what is wrong in my approach. Please help me understand. Thanks a lot in advance :)
The basic steps how to solve this problem:
0. cast string to array of integers
make a loop K times
in this loop go from i+1 (LOOP VAR) to end of a collection and search for higher value
when we find higher value then collection[i], we will remember its value and index on witch it is. Important thing to note is that we want to swap biggest number but i also has to be last possible number.
at the end of iteration we swap the elements (i with best index)
we are done so all its left is convert our int list back to string.
code: (its python because java is pain)
def sort(swaps, string):
l = list(map(int, list(string)))
print(l)
for i in range(swaps):
best = l[i] + 1
bestIndex = i
for j in range(i+1, len(l)):
if best <= l[j]:
best = l[j]
bestIndex = j
print(i, bestIndex)
l[i], l[bestIndex] = l[bestIndex], l[i]
return "".join(map(str, l))
print(sort(4, "61892795431"))
Your code is correct. The problem comes from the parameter 4 (max number of swaps). If you use 10, the sorting is completed successfully.
Maybe the deeper problems comes from the fact that you are comparing the swaps of your algorithm with the swaps that you would do efficiently to sort the numbers. Your algorithm may work but probably it is not the most efficient, so the number of swaps needed is above the optimum.

My java program won't run properly i want it to input several numbers into an array and put the into another array in order from lowest to highest

I want to make a program in java that takes user input of several numbes and displays them to the screen in order from the highest to lowest
But it wont work and i don't know why.
Thanks in advance
Note (this my firs time posting anything here)
public class project {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int[] arr1 = new int[5];
int arr2[] = new int[5];
System.out.println("enter 5 numbers");
for (int i=0; i<=4; i++){
int Uinput = input.nextInt();
arr1[i] = Uinput;
}
for(int b = 0; b <= 4; b++){
for (int a = 0; a <=100;a++){
for(int j = 0; j <=4; j++){
if ( a== arr1[j]){
arr2[b]=arr1[j];
}
}
}
}
System.out.println(arr2 [0]);
System.out.println(arr2 [1]);
System.out.println(arr2 [2]);
System.out.println(arr2 [3]);
System.out.println(arr2 [4]);
}
}
The problem with your loops is that you are continuing with the comparison even after you have set your element in arr2. That is why they all end up as the highest number.
You only want to set each element once. You could try and put breaks into each for loop, but i the easier solution would be;
int b = 0;
while(b < 5) {
for (int a = 0; a <=100;a++){
for(int j = 0; j <=4; j++){
if (a == arr1[j]){
arr2[b]=arr1[j];
b++;
}
}
}
}
By incrementing b every time you set the element, you are making sure each element is only set once.
This said, KevinO is correct and there are other better ways to sort the numbers (for example, your current code can't handle numbers greater than 100). I would recommend checking out the link

I need help in this (Sums In Loops)

Hello Guys i just need help this is the problem I want to solve:
Input data will contain the total count of pairs to process in the
first line.
The following lines will contain pairs themselves - one pair at each
line.
Answer should contain the results separated by spaces.
Example:
data:
3
100 8
15 245
1945 54
answer:
108 260 1999
i write the code and here it is
public class SumsInLoopAdvanced {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
int num = reader.nextInt();
int a =0;
int arr [] = new int[250];
for (int i = 0; i < num; i++) {
arr[i] = reader.nextInt();
}
for (int j = 0; j < num; j++) {
arr[j] = reader.nextInt();
}
for (int i = 0; i < num; i++) {
for (int j = 0; j < num; j++) {
a = arr[j]+arr[i];
}
System.out.print("Answer: \n" + a);
}
}
}
it just 245+15 the wrong answer so could you help me ??
your code is broken here:
for (int j = 0; j < num; j++) {
arr[j] = reader.nextInt();
}
because you are overwriting the previously filled array: arr[i]
int arr [] = new int[250];
for (int i = 0; i < num; i++) {
arr[i] = reader.nextInt();
}
If i got it right you need to print a sum of two arrays entries for each index.
First of all you are using the same array and you are overwriting everything that you did in a first loop by the second loop.
int arr [] = new int[250];
for (int i = 0; i < num; i++) {
arr[i] = reader.nextInt();
}
for (int j = 0; j < num; j++) {
//writing into the same array starting with 0 index
arr[j] = reader.nextInt();
}
And if I got this exercise right you don't need a nested loop, you need to to find a sum of two array elements from different arrays with the same index.
something like this:
for (int i = 0; i < num; i++) {
a = arr1[i] + arr2[i];
System.out.print(a + " ");
}
You're overwriting the values in arr on your second loop.
If you want to collect two sets of values, you'll need two arrays. (Well, not need, but that would be the reasonable way.) Also note that you don't need or want the nested loop at the end; just add the ith entry from the first array to the ith entry of the second.
Side note: Instead of a hardcoded upper bound on the array (250), use num so you know it's always big enough (e.g., if I tell you I'm going to enter 300 numbers, your code will blow up). int[] arr = new int[num];
But, now that the problem you're trying to solve is quoted in the question, note that your code doesn't want to read in a bunch of values, then read in a second bunch of values, and then add those together. The assignments says you'll enter things like "100 8" and then "15 245" and be meant to add those to get 108 and 260.
So you'll need to read the first number, then the second, add those and store them in your (one) array; then read the next third number, and the fourth, add those together and store them; and then output the results.

How do I sort numbers from an array into two different arrays in java?

I have to create a program that takes an array of both even and odd numbers and puts all the even numbers into one array and all the odd numbers into another. I used a for loop to cycle through all the numbers and determine if they are even or odd, but the problem I'm having is that since the numbers in the original array are random, I don't know the size of either the even or the odd array and therefore can't figure out how to assign numbers in the original array to the even/odd arrays without having a bunch of spots left over, or not having enough spots for all the numbers. Any ideas?
Try using an ArrayList. You can use
num % 2 == 0
to see if num is even or odd. If it does == 0 then it is even, else it is odd.
List<Integer> odds = new ArrayList();
List<Integer> evens = new ArrayList();
for (int i = 0; i< array.length; i++) {
if (array[i] % 2 == 0) {
evens.add(array[i]);
}
else {
odds.add(array[i]);
}
}
to convert the ArrayLists back to arrays you can do
int[] evn = evens.toArray(new Integer[evens.size()]);
(Note: untested code so there could be a few typos)
EDIT:
If you are not allowed to use ArrayLists then consider the following that just uses Arrays. It's not as efficient as it has to do two passes of the original array
int oddSize = 0;
int evenSize = 0;
for (int i = 0; i< array.length; i++) {
if (array[i] % 2 == 0) {
evenSize++;
}
else {
oddSize++;
}
}
Integer[] oddArray = new Integer[oddSize];
Integer[] evenArray = new Integer[evenSize];
int evenIdx = 0;
int oddIdx = 0;
for (int i = 0; i< array.length; i++) {
if (array[i] % 2 == 0) {
evenArray[evenIdx++] = array[i];
}
else {
oddArray[oddIdx++] = array[i];
}
}
You can do it without using arrays or any '%' Just a simple idea
input = new Scanner(System.in);
int x;
int y = 0; // Setting Y for 0 so when you add 2 to it always gives even
// numbers
int i = 1; // Setting X for 1 so when you add 2 to it always gives odd
// numbers
// So for example 0+2=2 / 2+2=4 / 4+2=6 etc..
System.out.print("Please input a number: ");
x = input.nextInt();
for (;;) { // infinite loop so it keeps on adding 2 until the number you
// input is = to one of y or i
if (x == y) {
System.out.print("The number is even ");
System.exit(0);
}
if (x == i) {
System.out.print("The number is odd ");
System.exit(0);
}
if (x < 0) {
System.out.print("Invald value");
System.exit(0);
}
y = y + 2;
i = i + 2;
}
}
Use a List instead. Then you don't need to declare the sizes in advance, they can grow dynamically.
You can always use the toArray() method on the List afterwards if you really need an array.
The above answers are correct and describe how people would normally implement this. But the description of your problem makes me think this is a class assignment of sorts where dynamic lists are probably unwelcome.
So here's an alternative.
Sort the array to be divided into two parts - of odd and of even numbers. Then count how many odd/even numbers there are and copy the values into two arrays.
Something like this:
static void insertionSort(final int[] arr) {
int i, j, newValue;
int oddity;
for (i = 1; i < arr.length; i++) {
newValue = arr[i];
j = i;
oddity = newValue % 2;
while (j > 0 && arr[j - 1] % 2 > oddity) {
arr[j] = arr[j - 1];
j--;
}
arr[j] = newValue;
}
}
public static void main(final String[] args) {
final int[] numbers = { 1, 3, 5, 2, 2 };
insertionSort(numbers);
int i = 0;
for (; i < numbers.length; i++) {
if (numbers[i] % 2 != 0) {
i--;
break;
}
}
final int[] evens = new int[i + 1];
final int[] odds = new int[numbers.length - i - 1];
if (evens.length != 0) {
System.arraycopy(numbers, 0, evens, 0, evens.length);
}
if (odds.length != 0) {
System.arraycopy(numbers, i + 1, odds, 0, odds.length);
}
for (int j = 0; j < evens.length; j++) {
System.out.print(evens[j]);
System.out.print(" ");
}
System.out.println();
for (int j = 0; j < odds.length; j++) {
System.out.print(odds[j]);
System.out.print(" ");
}
}
Iterate through your source array twice. The first time through, count the number of odd and even values. From that, you'll know the size of the two destination arrays. Create them, and take a second pass through your source array, this time copying each value to its appropriate destination array.
I imagine two possibilities, if you can't use Lists, you can iterate twice to count the number of even and odd numbers and then build two arrays with that sizes and iterate again to distribute numbers in each array, but thissolution is slow and ugly.
I imagine another solution, using only one array, the same array that contains all the numbers. You can sort the array, for example set even numbers in the left side and odd numbers in the right side. Then you have one index with the position in the array with the separation ofthese two parts. In the same array, you have two subarrays with the numbers. Use a efficient sort algorithm of course.
Use following Code :
public class ArrayComparing {
Scanner console= new Scanner(System.in);
String[] names;
String[] temp;
int[] grade;
public static void main(String[] args) {
new ArrayComparing().getUserData();
}
private void getUserData() {
names = new String[3];
for(int i = 0; i < names.length; i++) {
System.out.print("Please Enter Student name: ");
names[i] =console.nextLine();
temp[i] = names[i];
}
grade = new int[3];
for(int i =0;i<grade.length;i++) {
System.out.print("Please Enter Student marks: ");
grade[i] =console.nextInt();
}
sortArray(names);
}
private void sortArray(String[] arrayToSort) {
Arrays.sort(arrayToSort);
getIndex(arrayToSort);
}
private void getIndex(String[] sortedArray) {
for(int x = 0; x < sortedArray.length; x++) {
for(int y = 0; y < names.length; y++) {
if(sortedArray[x].equals(temp[y])) {
System.out.println(sortedArray[x] + " " + grade[y]);
}
}
}
}
}

Categories

Resources