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.
Related
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.
So guys, I'm developping a program for Structural Analysis and I came across a problem that I'm having some problem to solve. Basically, I have a system of equations, of which I only need to solve some of them.
The ones I need to solve depend on a boolean array, true if I do, false if I don't. This way, having a true value in the nth element of the array means I'll have to solve the nth equation, therefore meaning that I have to get the nxn element of the matrix of the system of equations.
Do you guys have any insight on it?
So, this is what I've come up with:
//Firstly, define the size of the subsystem:
int size = 0;
for(int i = 0; i < TrueorFalseMatrix.m; i++) {
if(TrueorFalseMatrix.data[i][0] != 0)
size+= 1;
}
//Then we can assign the size values to the Matrix of the subsystem
System_A = Matrix.matrizEmpty(size,size);
System_B = Matriz.matrizEmpty(size, 1);
//This array will store the coordinates of the coefficients that
//will be used
int[] Coordinates = new int[size];
//We store these coordinates in the array
int count = 0;
for(int i = 0; i < TrueorFalseMatrix.m; i++) {
if(TrueorFalseMatrix.data[i][0] != 0) {
Dtrue[count] = i;
count++;
}
}
//We can now assign values to our system Matrix
for(int i = 0; i < size; i++) {
for(int j = 0; j < size; j++) {
System_A.data[i][j] = SourceMatrix.data[Dtrue[i]][Dtrue[j]];
}
System_B.data[i][0] = SourceResultVector.data[Dtrue[i]][0]
}
//Results
double[] Results = System.solve(System_A,System_B);
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.
I am having trouble creating multiple arrays with a loop in Java. What I am trying to do is create a set of arrays, so that each following array has 3 more numbers in it, and all numbers are consecutive. Just to clarify, what I need to get is a set of, let's say 30 arrays, so that it looks like this:
[1,2,3]
[4,5,6,7,8,9]
[10,11,12,13,14,15,16,17,18]
[19,20,21,22,23,24,25,26,27,28,29,30]
....
And so on. Any help much appreciated!
Do you need something like this?
int size = 3;
int values = 1;
for (int i = 0; i < size; i = i + 3) {
int[] arr = new int[size];
for (int j = 0; j < size; j++) {
arr[j] = values;
values++;
}
size += 3;
int count = 0;
for (int j : arr) { // for display
++count;
System.out.print(j);
if (count != arr.length) {
System.out.print(" , ");
}
}
System.out.println();
if (i > 6) { // to put an end to endless creation of arrays
break;
}
}
To do this, you need to keep track of three things: (1) how many arrays you've already created (so you can stop at 30); (2) what length of array you're on (so you can create the next array with the right length); and (3) what integer-value you're up to (so you can populate the next array with the right values).
Here's one way:
private Set<int[]> createArrays() {
final Set<int[]> arrays = new HashSet<int[]>();
int arrayLength = 3;
int value = 1;
for (int arrayNum = 0; arrayNum < 30; ++arrayNum) {
final int[] array = new int[arrayLength];
for (int j = 0; j < array.length; ++j) {
array[j] = value;
++value;
}
arrays.add(array);
arrayLength += 3;
}
return arrays;
}
I don't think that you can "create" arrays in java, but you can create an array of arrays, so the output will look something like this:
[[1,2,3],[4,5,6,7,8,9],[10,11,12,13...]...]
you can do this very succinctly by using two for-loops
Quick Answer
==================
int arrays[][] = new int[30][];
for (int j = 0; j < 30; j++){
for (int i = 0; i < (j++)*3; i++){
arrays[j][i] = (i++)+j*3;
}
}
the first for-loop tells us, via the variable j, which array we are currently adding items to. The second for-loop tells us which item we are adding, and adds the correct item to that position.
All you have to remember is that j++ means j + 1.
Now, the super long-winded explanation:
I've used some simple (well, I say simple, but...) maths to generate the correct item each time:
[1,2,3]
here, j is 0, and we see that the first item is one. At the first item, i is also equal to 0, so we can say that, here, each item is equal to i + 1, or i++.
However, in the next array,
[4,5,6,7,8,9]
each item is not equal to i++, because i has been reset to 0. However, j=1, so we can use this to our advantage to generate the correct elements this time: each item is equal to (i++)+j*3.
Does this rule hold up?
Well, we can look at the next one, where j is 2:
[10,11,12,13,14...]
i = 0, j = 2 and 10 = (0+1)+2*3, so it still follows our rule.
That's how I was able to generate each element correctly.
tl;dr
int arrays[][] = new int[30][];
for (int j = 0; j < 30; j++){
for (int i = 0; i < (j++)*3; i++){
arrays[j][i] = (i++)+j*3;
}
}
It works.
You have to use a double for loop. First loop will iterate for your arrays, second for their contents.
Sor the first for has to iterate from 0 to 30. The second one is a little less easy to write. You have to remember where you last stop and how many items you had in the last one. At the end, it will look like that:
int base = 1;
int size = 3;
int arrays[][] = new int[30][];
for(int i = 0; i < 30; i++) {
arrays[i] = new int[size];
for(int j = 0; j < size; j++) {
arrays[i][j] = base;
base++;
}
size += 3;
}
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);
}
}