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
For an assignment I must read values from a file, and print them on the screen unless they are duplicate values. My approach was to create two arrays with the same values, then somehow compare them and if they are not equal, it would not print. Here is what I have:
import java.io.*;
import java.util.Scanner;
public class Set8_Prog4
{
public static void main (String[] args) throws IOException
{
FileReader i = new FileReader("Set8_Prog4 numbers.txt");
Scanner j = new Scanner(i);
int length = 0;
while (j.hasNextInt())
{
length++;
}
int[] values = new int[length];
int[] values2 = new int[length];
int k = 0;
while (j.hasNextInt())
{
values[k] = j.nextInt();
k++;
}
k = 0;
while (j.hasNextInt())
{
values2[k] = j.nextInt();
k++;
}
k = 0;
int m = 0;
while (values[k] != values2[m] && k < values.length)
{
while (m < values.length)
{
m++;
}
System.out.println(values[k]);
k++;
}
j.close();
}
}
It compiles, but you can probably tell it doesn't get the job done. I have been frying my brain trying to figure out how to get it to work. I could use some help. Oh and we can't use things like Array Lists, Hashsets, or anything like that. Just arrays.
UPDATED CODE:
import java.io.*;
import java.util.Scanner;
public class Set8_Prog4
{
public static void main (String[] args) throws IOException
{
FileReader i = new FileReader("Set8_Prog4 numbers.txt");
Scanner j = new Scanner(i);
int length = 0;
while (j.hasNextInt())
{
length++;
}
int[] values = new int[length];
int[] values2 = new int[length];
int k = 0;
while (j.hasNextInt())
{
values[k] = j.nextInt();
k++;
}
k = 0;
while (j.hasNextInt())
{
values2[k] = j.nextInt();
k++;
}
int m;
for (k = values.length; k >= 0; k--)
{
boolean found = false;
for (m = 0; m < values.length; m++)
{
if ((values[k] == values2[m]) && (k != m))
{
found = true;
continue;
}
if (!found)
{
System.out.println(values[k]);
}
}
}
}
}
I get nothing when I run it. No errors though.
You can add values to the array as you print them and each time you print the next value check an make sure it is not already in the array if it is don't print if it is not print and add the value to the array. You should only need one array for this.
Basically, you're never comparing values[k] with values2[m] properly, because when you do, m always equals values.length().
Change your nested while loops to the below:
for (int k=0; k < values.length; k++) {
boolean found = false;
for (int m=0; m < values.length; m++)
if ((values[k] == values2[m]) && (k != m)) {
found = true;
continue;
}
if (!found)
System.out.println(values[k]);
}
Or, for more efficient code (and better marks), check if the integer is present in the array when it is read from the file. If the integer is already there, don't add it to the array, otherwise, do. As the other answer states, this approach would only require 1 array, and is more memory efficient as a result.
Another tip to increase your marks - think about your variable names (values and values2 aren't brilliant names)
Ok, so here is a sample method that will add values to an array, only if they don't already exist in it:
// int[] array containing values
// value currently being added
// index where the value is currently being added
void addValueWithoutDuplication(int[] array, int value, int index) {
for(int i = 0; i < index; i++) { // iterate over all the values that are currently in the array
if(array[i] == value) { // if the value we are adding is a duplicate of a value in the array
return; // return out of this method and don't add the value
}
}
array[index] = value; // if we reached this point, value is not a duplicate and we can add it to the array at the index
}
If you add each value using this method, your array will not contain any duplicates and then you can just iterate over the array and print the values.
Since values and values2 have the exact same contents and you set k = 0 and m = 0 you will never actually get into your while loop while (values[k] != values2[m] && k < values.length). Also(if you continue using your current approach), once you figure out what you need to iterate over for that while loop, consider the fact that once you do get into that loop, m goes from the index that gets you into the array all the way to values.length which may or may not throw an index of bounds exception when you test while (values[k] != values2[m] && k < values.length) the next time :) Since this is homework, I'll let you figure the rest out.
Related
I have created a function that takes an array and outputs another array. So I have declared the result array (which will be the output) as null cause the size varies and depends on the inputted array. (for eg. if I enter an array of integers and then I want to output the array containing even numbers from that array). So I will be using for or while loops and I want to know that how I can add the integer to that null array. I tried but I get a null pointer exception that says cannot store to int array cause "array" is null.
sorry but I can't use more advanced techniques cause I am new to java (I need to make this without using arraylist library as I am learning coding I found those type of questions which tries to make you perfect in i specific topic and then they take you to next step so u can be more prepared)
I am using this code and I want to know that add an element to my result array or should I initialized it as null or something else cause the size depends on inputted array in this code I am getting null pointer exception
public static int[] even(int[] numbers) {
int[] result = null;
int even = 0;
int i = 0;
int a = 0;
while (i < numbers.length) {
if (numbers[i] % 2 == 0) {
even = numbers[i];
result[a] = even;
a++;
}
i++;
}
return result;
}
The array's size needs to be initialized. If you want dynamic storage , read about List and Collection.
Here, if you still want to use array, you need the count.
int a = 0;
while (i < numbers.length) {
if (numbers[i] % 2 == 0) {
a++;
}
i++;
}
Then after this, you can initialize it as int[] result = new int[a];
public static int[] even(int[] numbers) {
int[] result = null;
int j = 0;
int a = 0;
while (i < numbers.length) {
if (numbers[j] % 2 == 0) {
a++;
}
j++;
}
result = new int[a];
int even = 0;
int i = 0;
int b = 0;
while (i < numbers.length) {
if (numbers[i] % 2 == 0) {
even = numbers[i];
result[b] = even;
b++;
}
i++;
}
return result;
}
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 8 years ago.
Improve this question
I want to create a union array for two integer arrays using nested loops.
This is my attempt so far:
import java.util.Scanner ;
public class array4 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter first array size:");
int size = input.nextInt();
int x[] = new int[size];
System.out.println("Enter first array elements:");
for (int i = 0; i < size; i++) {
x[i] = input.nextInt();
}
System.out.print("Enter second array size:");
int size2 = input.nextInt();
int y[] = new int[size2];
for (int i = 0; i < size2; i++) {
y[i] = input.nextInt();
}
System.out.println("Union");
for (int i = 0; i < size; i++) {
System.out.println(x[i]);
}
for (int i = 0; i < size2; i++) {
for (int z = 0; z < size; z++) {
if (y[i] != x[z]) {
System.out.println(y[i]);
}
}
}
}
}
Lets assume that we will print all numbers from second array, and only these numbers from first array which don't exist in second one. So
for each element in first array
test if it exist in second array (iterate over elements in second array and set some boolean flag like exists to true if x[i]==y[j])
if element doesn't exist in second array print it
iterate over elements from second array
and print them
Algorithm can look like
for (int i = 0; i <= x.length; i++) {// "<=" is not mistake,
// in last iteration we print all elements
// from second array
boolean exist = false;
for (int j = 0; j < y.length; j++) {
if (i < x.length) {
if (x[i] == y[j])
exist = true;
} else
System.out.println(y[j]);
}
if (!exist && i < x.length)
System.out.println(x[i]);
}
This algorithm can be probably rewritten to something simpler but I will leave it in this form for now.
For the lack of requirements, here is my answer for now... just basing on your current code.
for (int i = 0; i < size2; i++) {
for (int z = 0; z < size; z++) {
if (y[i] != x[z]) {
System.out.println(y[i]);
break; //added break
}
}
}
The problem was you're printing array elements without duplicate multiple times, to avoid that, you should add a break after you print the element with no duplicate.
By the way, your code is just printing the elements on both arrays, I thought you're suppose to combine them? Shouldn't you have a new array that contains both of the elements on the two arrays?
EDIT 2:
Add these lines of code after you get the two set of arrays without duplicate:
I also added comments to explain what's happening.
System.out.println("Union");
int[] unionArray = new int[size + size2]; //created a new array that will contain two arrays
for (int i = 0; i < size; i++) { //put the first set of int in the new array
unionArray[i] = x[i];
}
for (int i = size; i < unionArray.length; i++) { //put the second set
unionArray[i] = y[i-size]; //i = size : started with the last index of the first array
//y[i-size] : we are getting the elements on the second array
}
for (int i = 0; i < unionArray.length; i++) { //output
System.out.println(unionArray[i]);
}
Hope this helps. :)
If it's just to play with arrays and you don't need to use loops - try using a Java collection for that task, that's how most people would probably implement it:
init collection 1 from array 1
init collection 2 from array 2
add collection 2 to collection 1
convert collection 1 back to an array
That can be a (more or less) neat one-liner.
I have a dilemma on my hands. After much trial and error, I still could not figure out this simple task.
I have one array
String [] array = {anps, anps, anps, bbo, ehllo};
I need to be able to go through the array and find duplicates and print them on the same line. Words with no duplicates should be displayed alone
The output needs to be like this
anps anps anps
bbo
ehllo
I have tried while, for loops but the logic seems impossible.
Okay, there are a worryingly number of either wrong answers or answers that use HashMap or HashSet for this very simple iteration problem, so here is a correct solution.
Arrays.sort(array);
for (int i = 0; i < array.length; ++i){
if (i+1 == array.length) {
System.out.println(array[i]);
} else if (array[i].equals(array[i+1])) {
System.out.print(array[i]+" ");
} else {
System.out.println(array[i]);
}
}
Sort the array first then
for(int i = 0, i < array.length; i++){
String temp = array[i];
System.out.print(temp+" ");
for(int j = i+1; j < array.length; j++){
String temp2 = array[j];
if(temp.compareTo(temp2) == 0){
System.out.print(temp2+" ");
i++;
}
}
System.out.println();
}
or something similar...
There are multiple ways of achieving this.
Use two for loops, one that loops through the array and picks a value and another inner loop where you go through the array (from the current index) looking for that value
You could have a map that contains the words, you loop through the array and you fill out the map with the number of occurrences corresponding to the value currently fetched from the array
The second way is better. The code is something like:
Map<String, Integer> occurences = new HashMap<String, Integer>();
for(int index=0; index < array.length; index++){
int nOcc = 1;
if(occurences.containsKey(array[index]){
nOcc = occurences.get(array[index]) + 1;
}
occurences.remove(array[index]);
occurences.put(array[index], nOcc);
}
At this point, the map should contain all words (keys) and their corresponding number of occurrences (values)
If you sort the array first, then you can just check if the current index is equal to the next index (bearing in mind that you must account for IndexOutOfBounds), if they are equal do a System.out.print() if they are not equal do a System.Out.println().
String [] array = {"anps", "anps", "anps", "bbo", "ehllo"};
// If you already are assured that the strings in the array are sorted
// then the sort is not necessary.
Arrays.sort(array);
for(int i = 0; i < array.length; i++){
if((i+1)==array.length || !array[i].equals(array[(i+1)])){
System.out.println(array[i]);
} else {
System.out.print(array[i]+" ");
}
}
Complexity n^2 , just start from first value and go to the end finding the same, if you found print in one line and go to the new line, also you should delete all printed value.
Complexity nlogn + n == nlogn , merge or quick sort, and after this go to the end and pring sequenced values.
There are more solutions but I think its enough for you.
Naive Algorithms
Create a Map
Iterate through all array
check if key already exist in map
if yes update value +1
if no insert
print the map as you want
You should be able to do what you're looking for !
Use below logic
import java.util.ArrayList;
public class RepeatStringPrint {
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
String[] x = { "anps", "anps", "anps", "bbo", "ehllo" };
String total[] = new String[50];
String sTotal[] = null;
for (int i = 0; i < x.length; i++) {
total[i] = x[i];
}
for (int k = 0; k < total.length; k++) {
int count = 0;
if (total[k] != null) {
sTotal = new String[50];
for (int i = 0; i < total.length; i++) {
if (total[k] == total[i]) {
count++;
if (count <= 1) {
sTotal[i] = total[k];
}
}
}
if (sTotal[k] != null) {
for(int j=0; j<count; j++){
System.out.print(sTotal[k]+"\t");
}
System.out.print("\n");
}
}
}
}
catch (Exception e) {
}
}
}
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);
}
}
How do I find the mode (most frequent value in an array) using a simple for loop?
The code compiles with a wrong output.
Here is what I have:
public static void mode(double [] arr)
{
double mode=arr[0];
for(int i = 1; i<arr.length; i++)
{
if(mode==arr[i])
{
mode++;
}
}
return mode;
}
First I sort the array by order and then I count occurrences of one number. No hashmaps only for loop and if statements.
My code:
static int Mode(int[] n){
int t = 0;
for(int i=0; i<n.length; i++){
for(int j=1; j<n.length-i; j++){
if(n[j-1] > n[j]){
t = n[j-1];
n[j-1] = n[j];
n[j] = t;
}
}
}
int mode = n[0];
int temp = 1;
int temp2 = 1;
for(int i=1;i<n.length;i++){
if(n[i-1] == n[i]){
temp++;
}
else {
temp = 1;
}
if(temp >= temp2){
mode = n[i];
temp2 = temp;
}
}
return mode;
}
-Just use a HashMap which contains the array index values as the keys and their occurrence numbers as the values.
-Update the HashMap as you traverse the for loop by checking to see if the current index already exists in the HashMap. IF IT DOES then find that double in the hash map and see how many times it has already occurred and put it back in the HashMap with one more occurrence.
-I did it in Java because that's what it looks like you are using. What's also good is that the time complexity is O(n) which is the best you could possibly get for this type of scenario because you have to visit every element at least once.
-So if you have an array like this of doubles: { 1,2,3,1,1,1,5,5,5,7,7,7,7,7,7,7,7,7}
Then the hash map will look something like this at the end: { 1->4, 2->1, 3->1, 5->3, 7->9 }
Meaning that "1 occurred 4 times, 2 occured 1 time .... 7 occurred 9 times" etc.
public static double mode(double [] arr)
{
HashMap arrayVals = new HashMap();
int maxOccurences = 1;
double mode = arr[0];
for(int i = 0; i<arr.length; i++)
{
double currentIndexVal = arr[i];
if(arrayVals.containsKey(currentIndexVal)){
int currentOccurencesNum = (Integer) arrayVals.get(currentIndexVal);
currentOccurencesNum++;
arrayVals.put(currentIndexVal, currentOccurencesNum );
if(currentOccurencesNum >= maxOccurences)
{
mode = currentIndexVal;
maxOccurences = currentOccurencesNum;
}
}
else{
arrayVals.put(arr[i], 1);
}
}
return mode;
}
This code is a different way that does not use hashmaps. This method, created in java, takes an array as the parameter and creates another array called "numberCount" within the method. This array "numberCount" will set its index to the value in the array. The index of "numberCount"that contains the value in the array passed will add 1 to the value of "numberCount" ("++numberCount[array[i]]") then will go to the next value in the array (repeat until the end of the array). Then creates another for loop to go through each value of the array in "numberCount", which ever index has the highest value/count will be stored and return as "max." This method will have to undergo some difficult changes to use a double array. but seems to work great with an int array.
public static int findMostFrequentValue(int[] array) {
int i;
int[] numberCount = new int[100];
for (i = 0; i < array.length; i++)++numberCount[array[i]];
int max = 0;
int j;
for (j = 0; j < numberCount.length; j++) {
if (numberCount[j] > max) max = j;
}
return max;
}
You should check the number of occurances of every element in your array. You can do it by comparing every element of array with herself and others via 2 inner for loops.
Remember, if the array is not sorted and contains more then 1 modal value (thus repeating number of occurances) this will return the first one. It maybe wise to order the array first by Arrays.sort(array) so that you can pick the smallest or biggest modal value.
public static int modeOfArray(int[] array){
int mode;
int maxOccurance = 0;
for(int i=0; i<array.length; i++){
int occuranceOfThisValue = 0;
for(int j=0; j<array.length; j++){
if(array[i] == array[j])
occuranceOfThisValue++;
}
if(occuranceOfThisValue > maxOccurance){
maxOccurance = occuranceOfThisValue;
mode = array[i];
}
}
return mode;
}