Java - Result not outputting correctly [closed] - java

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I'm trying to finish a program that displays the average, hottest, & coldest temperatures of the week, and also displays which days are the hottest and coldest. The user enters in 7 temperatures from Sun - Sat. It is almost working but it seems as though there is a bug in the method near the bottom called searchTemp, this method sees how many times the highest/lowest temperature occurred in the array of temperatures, and then creates an array of size needed, and then it iterates over all the values, storing the indexes at which the high/low temperatures occurred in the original array, it then returns the new array with the values of the index locations. Ideally I would map these values to an array containing the strings Sunday through Saturday and print out all the days that the temperature was the highest or lowest. The issue is that right now if the user enters say 18 for the highest and then they enter 18 again, instead of the program outputting something like "Monday Wednesday" it outputs Wednesday Wednesday"
Can anyone help me?
public static int[] searchTemp(int[] array, int key) {
int count = 0;
for(int i = 0; i < array.length; i++) {
if(array[i] == key)
count++;
}
int[] indices = new int[count];
for(int j = 0; j < indices.length; j++) {
for(int i = 0; i < array.length; i++) {
if(array[i] == key)
indices[j] = i;
}
}
return indices;
}
}

The searchTemp should be changed as following:
public static int[] searchTemp(int[] array, int key) {
int count = 0;
for(int i = 0; i < array.length; i++) {
if(array[i] == key)
count++;
}
int[] indices = new int[count];
for(int j = 0; j < indices.length; j++) {
for(int i = 0; i < array.length; i++) {
if(array[i] == key) {
if(j > 0 && indices[j - 1] == i){
continue;
}
else {
indices[j] = i;
break;
}
}
}
}
return indices;
}
This will return the correct hottest/coldest.
Hope this help!

I believe it is here
int[] indices = new int[count];
for(int j = 0; j < indices.length; j++) {
for(int i = 0; i < array.length; i++) {
if(array[i] == key)
indices[i] = i; <---------
}
}
should be
indices[j] not i as you are using the inner array's length on this.

Related

How to change one value equal to another in an int array in java? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
I am trying to make the code so it wont print the same number twice or more. I have no clue how to make it that way. what do I need to change/add to make it print only one of each number?
public class LottoSpill {
public static int ran() {
int random = (int)(Math.random()*34+1);
return random;
}
public static int lottoRekke() {
int[] array = {ran(), ran(), ran(), ran(), ran(), ran(), ran()};
int ret = array[0];
for (int i = 0; i < array.length; i++){
for (int j = 1; j < array.length; j++){
if(array[i] == array[j]) {
array[i] = array[i] - array[j] + ran();
do {
j++;
i++;
} while(i < array.length || j < array.length);
for (int k = 0; k < array.length; k++) {
System.out.print(array[k] + " ");
}
} else if(array[i] != array[j]) {
do {
j++;
} while(j < array.length);
}
}
}
return ret;
}
public static void main(String[] args) {
lottoRekke();
}
}
this is the result of the code, as you can see the number 17 have been printed twice
25 10 17 20 17 6 27 [Finished in 0.3s]
Try this.
Generate a List of the numbers from 1 to 34. (or whatever your range is).
List<Integer> list = new ArrayList<>();
for (int i = 1; i <= 34; i++) {
list.add(i);
}
then call Collections.shuffle() on the list.
Collections.shuffle(list);
then just take the first 6 (or however many) numbers. They will be random and unique.
for (int i = 0; i < 6; i++) {
System.out.println(list.get(i));
}
EDIT
You can pass the starting and ending numbers or leave them out and hard code them in the method.
public static List<Integer> lottery(int start, int end) {
List<Integer> nums = new ArrayList<>();
for (int i = start; i <= end; i++) {
nums.add(i);
}
Collections.shuffle(nums);
return nums;
}
// e.g.
List<Integer> vals = lottery(1,34);

Java : Selection Sort Logic

I am printing Sorted Array elements using Selection Sort. But I am getting my input array elements as output in same sequence without sorting.
public class SelectionSort {
public static void main(String[] args) {
int[] arr= {1,9,3,0,7};
int n=arr.length;
for(int i=0; i<n-1; i++)
{
int minimumIndex = i;
for(int j=i; j<n; j++)
{
if(arr[j]<arr[minimumIndex])
{
minimumIndex=j;
}
}
int temp=arr[i];
arr[i]=arr[minimumIndex];
arr[i]=temp;
}
for(int e: arr)
{
System.out.print(e+" ");
}
}
}
Expected o/p : 0 1 3 7 9
Actual o/p: 1 9 3 0 7
In Your method code, the actual problem is swapping elements,
the Sequence needs to be like this as below,
int temp=arr[minimumIndex];
arr[minimumIndex]=arr[i];
arr[i] =temp;
instead of
int temp=arr[i];
arr[i]=arr[minimumIndex];
arr[i]=temp;
There are two issues I see. One is the way you are swapping the items. You need to replace the item where you found the minimum index. Also, your J index should start one after your I index. You can assume that the one before it is the smallest as you are looping through. I have changed a few pieces of the code and tested it and it works fine for me.
for (int i = 0; i < arr.length - 1; i++)
{
int minimumIndex = i;
for (int j = i + 1; j < arr.length; j++)
{
if (arr[j] < arr[minimumIndex])
{
minimumIndex = j;
}
}
int temp = arr[i];
arr[i] = arr[minimumIndex];
arr[minimumIndex] = temp;
}

Find number of duplicate that occurs in array - Java

I can't wrap my head around this. Need to find duplicates and I did. All now that is left is to print how many times a duplicate appears in the array. I just started with Java,so this needs to be hard coded for me to understand. Spend last two days trying to figure it out but with no luck.. Any help will be great! Talk is cheap,here is the code..
import java.util.Arrays;
public class LoopTest {
public static void main(String[] args) {
int[] array = {12,23,-22,0,43,545,-4,-55,43,12,0,-999,-87};
int positive_counter = 0;
int negative_counter = 0;
for (int i = 0; i < array.length; i++) {
if(array[i] > 0) {
positive_counter++;
} else if(array[i] < 0) {
negative_counter++;
}
}
int[] positive_array = new int[positive_counter];
int[] negative_array = new int[negative_counter];
positive_counter = 0;
negative_counter = 0;
for (int i = 0; i < array.length; i++) {
if(array[i] > 0) {
positive_array[positive_counter++] = array[i];
} else if(array[i] < 0) {
negative_array[negative_counter++] = array[i];
}
}
System.out.println("Positive array: " + (Arrays.toString(positive_array)));
System.out.println("Negative array: " + (Arrays.toString(negative_array)));
Arrays.sort(array);
System.out.println("Array duplicates: ");
for (int i = 0; i < array.length; i++) {
for (int j = i + 1; j < array.length; j++) {
if(array[i] == array[j]) {
System.out.println(array[j]);
}
}
}
}
}
Since you are already sorting the array you can find the duplicates with just one loop (they will be next to each other right?). So you can do something like:
Arrays.sort(array);
System.out.println("Array duplicates: ");
int lastValueCount=1; //How many times we met the current value (at least 1 - this time)
for (int i = 1; i < array.length; i++){
if(array[i] == array[i-1])
lastValueCount++; //If it is the same as the previous increase the count
else {
if(lastValueCount>1) //If it is duplicate print it
System.out.println(array[i-1]+" was found "+lastValueCount+" times");
lastValueCount=1; //reset the counter
}
}
Result for your array is:
Array duplicates:
0 was found 2 times
12 was found 2 times
43 was found 2 times
Also you can use some of the Java bells and whistles like inserting the values into Map or something like that but I guess you are looking from an algorithmic point of view so the above is the simple answer with just one loop
Just go through your solution, first you separate positive and negative numbers in two different arrays, then you never use them, so what's the purpose of this separation ?
I am giving you just an idea related to your problem, it's better to solve it by your self so that you can get hands on Java.
Solution: you can use Dictionary-key value pair. Go through your array, put element in dictionary as a key and value as zero, on every iteration check if that key already exist in Dictionary, just increment its value. In the end, all of the values are duplicates that occurs in your array.
Hope it helps you.
From the algorithmic point of view, Veselin Davidov's answer is good (the most efficient).
In a production code, you would rather write it like this :
Map<Integer, Long> result =
Arrays.stream(array)
.boxed() //converts IntStream to Stream<Int>
.collect(Collectors.groupingBy(i -> i, Collectors.counting()));
The result is this Map :
System.out.println(result);
{0=2, 545=1, -4=1, -22=1, -87=1, -999=1, -55=1, 23=1, 43=2, 12=2}
An easy way would be using Maps. Without changing code too much:
for (int i = 0; i < array.length; i++) {
int count = 0;
for (int j = i + 1; j < array.length; j++) {
if(array[i] == array[j]) {
System.out.println(array[j]);
count++;
}
}
map.put(array[i], count);
}
Docs:
https://docs.oracle.com/javase/7/docs/api/java/util/Map.html
Edit: As a recommendation, after you are done with the example, you should analize your code and find what isnĀ“t neccesary, what could be done better, etc.
Are all your auxiliary arrays neccesary? Are all loops necessary?
You can do it by creating an array list for duplicate values:-
Arrays.sort(array);
System.out.println("Array duplicates: ");
ArrayList<Integer> duplicates = new ArrayList<Integer>();
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array.length; j++) {
if(j != i && array[i] == array[j] && !duplicates.contains(array[i])){
duplicates.add(array[i]);
System.Out.println(duplicates[duplicates.size()-1]);
}
}
}
public static void findDuplicate(String s){
char[] charArray=s.toCharArray();
ArrayList<Character> duplicateList = new ArrayList<>();
System.out.println(Arrays.toString(charArray));
for(int i=0 ; i<=charArray.length-1; i++){
if(duplicateList.contains(charArray[i]))
continue;
for(int j=0 ; j<=charArray.length-1; j++){
if(i==j)
continue;
if(charArray[i] == charArray[j]){
duplicateList.add(charArray[j]);
System.out.println("Dupliate at "+i+" and "+j);
}
}
}
}

How to check if an element has occured before in the array [duplicate]

This question already has answers here:
How do I get the intersection between two arrays as a new array?
(22 answers)
Closed 7 years ago.
For example, the following question states:
Write a method which takes two array of integers as parameter and prints all their common elements.
My attempt:
public static void commonElements(int[] A, int[] B)
{
for(int i = 0; i < A.length; i++)
for(int j = 0; j < B.length; j++)
if(A[i] == B[j])
System.out.print(A[i] + " ");
}
Now, the problem is that this code works only if the elements in each array occurs only once. But for example if in array A there were two 4s and in array B there were four 4s, the output would be eight 4s, which is wrong!
So, how can I check if a certain element in an array has already occured so that the code won't take it in account.
public static void commonElements(int[]A, int []B){
int count = 0;
for(int i = 0; i < A.length; i++)
for(int j = 0; j < B.length; j++)
if(A[i] == B[j]){
count++;
break;
}
System.out.println(count);
}
Give this a try. By adding break you force it out of the loop.
You can store what you found in a set. A set doesn't allow for duplicates.
public static void commonElements(int[] a, int[] b)
{
Set<Integer> duplicates = new LinkedHashSet<Integer> duplicates;
for(int i = 0; i < a.length; i++){
for(int j = 0; j < b.length; j++){
if(a[i] == b[j]){
duplicates.add(a[i]);
}
}
}
System.out.println(String.join(" ", duplicates));
}
Note: Variable names should be lowercase in Java, by convention.

Return position of value in a 2D array, Java [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
I'm tired. This must be simple. wood... for.... trees....
I'm trying to return the position of a specific value in a 2D array.
I have a double array [300][300].
All values contained in it are 0 apart from one which is 255.
How do I write a method to return the [i][j] location of 255?
Thanks in advance.
Simply iterate over all the elements until you find the one that is 255:
for ( int i = 0; i < 300; ++i ) {
for ( int j = 0; j < 300; ++j ) {
if ( array[i][j] == 255 ) {
// Found the correct i,j - print them or return them or whatever
}
}
}
This works:
public int[] get255() {
for(int i = 0; i < array.length; i++)
for(int j = 0; j < (array[i].length/2)+1; j++)
if(array[i][j] == 255)
return new int[] {i,j};
else if(array[j][i] == 255) //This just slightly increases efficiency
return new int[] {j,i};
return null; //If not found, return null
}
This is possibly the fastest, though. It checks starting in each corner, progressively working inward to the center, horizontally first, then vertically:
public int[] get255() {
for(int i = 0; i < (array.length/2)+1; i++)
for(int j = 0; j < (array[i].length/2)+1; j++)
// Check the top-left
if(array[i][j] == 255)
return new int[] {i,j};
// Check the bottom-left
else if(array[array.length-i][j] == 255)
return new int[] {array.length-i,j};
// Check the top-right
else if(array[i][array[i].length-j] == 255)
return new int[] {i,array[i].length-j};
// Check the bottom-right
else if(array[array.length-i][array[i].length-j])
return new int[] {array.length-i, array[i].length-j};
return null; //If not found, return null
}
You can use binary search for each column.
Use for loop to iterate over each column as it is an 2d array.
Once you get all the rows from the specific column you are iterating ( which would be another array), do a binary search on them.
Conditions Apply:
1. If the array is sorted .
2. If you are sure that only one element is there in each column. ( No duplicates).
3. If there are duplicates in the rows( do linear search) .
I hope it helps. Please feel free to ask if still in doubt :)
For any size of Array, you have put to the size first, though I have used a scanner to input value directly, you can bring it from another method also, I am learning so if I am wrong please correct me. On your case value will be 255 instead of 1.
public class MagicSquareOwn {
public static int[] findValueByElement(int n) {
Scanner input = new Scanner(System.in);
int[][] squareMatrix = new int[n][n];
int[] position = null;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
squareMatrix[i][j] = input.nextInt();
}
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (squareMatrix[i][j] == 1) {
position= new int[] { i, j };
System.out.println("position is:" + Arrays.toString(position));
}
}
}
return position;
}
public static void main(String[] args) {
Scanner inputOfMatrixNo = new Scanner(System.in);
int n = inputOfMatrixNo.nextInt();
MagicSquareOwn.findValueByElement(n);
}
}

Categories

Resources