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 4 years ago.
Improve this question
I need two input array A and array B.
The answer will be like this - if input A is
{5,2,6,8}
and input B is
{6,5,5,8,5,6}
then the output will be:
2 (0 times), 5 (3 times), 6 (2 times), 8 ( 1 times)
Here is an example of how you can achieve it.
public static void main(String[] args) {
int[] A={5,2,6,8},
B={6,5,5,8,5,6};
int[] count = new int[A.length]; // An array counting the occurences
StringBuilder result = new StringBuilder(); // The String to be displayed. StringBuilder is better than String, when multiple concatenations occur.
Arrays.sort(A); // Sorts array A in ascending order (by default).
// This loop counts the occurence of each value of A inside B
for (int i = 0; i <A.length; i++){
for (int j = 0; j < B.length; j++){
if (A[i] == B[j])
count[i]++;
}
// After each value of A, add the number of occurence in the String
result.append(A[i]).append(" (").append(count[i]).append(" times), ");
}
// Displays the String in the console, removing the last ", "
System.out.println(result.substring(0,result.length()-2));
}
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
Problem with output from a two dimensional array, basically 8 rows and 5 columns, each row represents one athlete, the five colums represent the points they have gained in each task. I have to find out If an athlete went beyond 250 points in a single task. Firstly, I made an integer which counts the number of times the Array has been look at, If the number can be divided by 5 it means the next number is going to be the next row and thus a new athlete, next I created another loop to check all the previous numbers and if any of them goes beyond 250, I add one number to the total + break the cycle. The result I have been getting back is 0, or before I got nothing.
for (i=0; i<8; i++) {
for (j=0; j<5; j++)
if(rezultati[i][j]>0) {
skaits = skaits + 1;
}
else if(skaits % 5==0) {
for (int a=0; a<5; a++) {
if(rezultati[i-a][j-a]>250) {
daudzums = daudzums + 1;
break;
}
}
}
}
realised that the row index should be just i if(rezultati[i][j-a]>250), didnt fix the issue tho
You already have an outer loop that will move to the next row/athlete for you. Simply look at the current value and if it exceeds 250, increment your counter and move to the next athlete with break:
int daudzums = 0;
int[][] rezultati = new int[8][5];
// ... populate zezultati somehow ...
for (int i=0; i<rezultati.length; i++) {
for (int j=0; j<rezultati[i].length; j++) {
if (rezultati[i][j]>250) {
daduzums++;
break; // move to next athlete
}
}
}
System.out.println("daudzums = " + daudzums);
After the loops, daudzums will tell you how many athletes had at least one task over 250.
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
what I attend to do is when the array(from 0 to n-1) is given, to sum the array values with the index minus multiple of 3 start from the end.
for example, when 7 arrays are given, I want to sum a[0] a[2] a[3] a[5] a[6].
below is error part of the code I programmed.
int j = 0;
for(int i=0; i<n; i++){
j = i*3;
if(i!=n-j)
r += array[i];
}
my code can't read the condition and just sum all the array values.
I don't know why. can someone help me ?
Let's debug!
first time through the loop:
i = 0
j = i * 3 soo... 0
if (0 != 7 - 0) ... - it's not, of course, so i = 0 qualifies and is added.
next loop:
i = 1
j = 3
if (1 != 7 - 3) ... - it's not, of course, so i = 1 qualifies and is added.
Which you did not want.
Given that this is homework, this should be enough for you to take another step and figure out what you SHOULD be doing here. I will give some tips:
You can loop, counting backwards, just as well. You'd have to use i-- of course (decrement i by 1 every time), and you'd use int i = n or perhaps int i = n - 1 as initializing expression in your for loop.
That whole 'is it a 3rd factor from the top' part cannot be calculated using i at all, you'd need something separate for this. You can declare variables outside (you already did that, int j = 0, but you're not looking for 0 so much as 'the first index from the top I do not want'. Then you can use if to check if it is that index. If so, you don't want to add that number to your sum AND you want to update your j.
For tasks like that the modulo operator is usually your friend.
I tried it like this and it works:
int r = 0;
int[] array = new int[7];
for(int i = array.length; i >= 0; i--){
int numberOfIteration = array.length - i;
if(numberOfIteration % 3 > 0){
System.out.println("Add array[" + i + "]");
r += array[i];
}
}
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
I am looking to write a function that prints out a character a certain amount of times.
I am thinking to take in the first two characters from a string and setting up a for loop that runs the number of the second character to print out the first character.
I have this so far but seem to be getting nowhere
public static String output(String a, String b,String c,String d) {
int a= Integer.parseInt(a.substring(0, 2));
for(int i=0;i<a;i++) {
}
If you divide the length of your String by two, you can get at the base number of letter/number pairs that you have. Then you can use a for loop which increments by two each time, and pulls out the next set of two chars and processes them. Something like this:
public static String output(String a) {
String output = "";
int length = a.length();
for (int i = 0; i < length; i+=2) {
String tempString = a.substring(i,i+2);
int x = Integer.parseInt(tempString.substring(1));
for (int t = 0; t < x; t++) {
output += tempString.substring(0,1);
}
}
return output;
}
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 7 years ago.
Improve this question
I couldn't find a solution for this in Java. I need to write code that will take an integer n, and an array of integers that has numbers up to n(some may be missing), and the method will print out which numbers are missing
ex: {2; 3; 5; 1; 2; 3} should print out 4, 6
Edit: Here is what I got from the comments suggestion, but it doesn't seem to work. What did I do wrong?
public static void findMissingNum(int n, int[]a) {
boolean A[] = new boolean[n];
for(int i = 0; i < a.length; i++) {
A[a[i]] = true;
}
for(int j = 0; j < A.length; j++) {
if (A[j] = false) {System.out.print(A[j]);}
}
}
I've seen this used as a homework or quiz problem before, the question is begging you to use a hash table. Create an empty Boolean array of size n and for each number in the list set array[num] to True. Loop over the new array, and record all the instances of False, you know ahead of time how many there should be.
The following ought to work:
public void find() {
Scanner s = new Scanner(System.in);
int[] nums = {2, 3, 5, 1, 2, 3};
int n = s.nextInt();
boolean[] included = new boolean[n+1];
for(int i = 0; i < nums.length; i++) included[nums[i]] = true;
for(int z = 0; z < included.length; z++) {
if(included[z] == false) System.out.print(z+ ",");
}
}
This will print out all missing numbers including n (if it is missing). If n is not included then do new boolean[n]
The way it works is by first using Scanner to read in your int n. It has two arrays, an int array which has your numbers, and a boolean array which serves as a set of flags. The boolean array is initalized to the size of n. Then it loops through the nums array and sees what numbers are included in the array. If the number is included, its element in the boolean arary is flagged as true. Finally, it loops through the flags/boolean array, if the element at that flag is true, do nothing since its already there, otherwise if its false (meaning the # wasn't included) then print it.
Try to implement this solution in Java:
Create second array A = [0,..,n] of booleans. Initialize it with false values.
Iterate through input array: for i = 0 to length(inputArray): A[inputArray[i]] := true.
Check which indexes in array have value false, those are the values that You want to return.
List< Integer > list = Arrays.asList(yourArray);
Then you can just create an array from 1 up to n with all numbers in order, and iterate through its elements checking for each one if your list contains it or not, adding it to another missingValues list if not.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
This is a game that generates a random 4 digit number and then lets the user input 5 chances to guess the game and returns a hint as to how many numbers were in the correct place and how many matched but were in the wrong place.
I am having a problem comparing two strings. One of the strings holds the correct answer to the game, the other string holds the most recent 4 digit guess.
aCount needs to be the number of characters that are in correct position.
bCount needs to be the number of characters that are in the correct answer, but not in correct position.
bCount is the part I'm having trouble with (it's not working as I expect). I thought I might try a double for loop, but I'm not sure.
static String getHint(String guess, String answer){
int aCount=0;
int bCount=0;
String hintString="";
for (int i =0; i<answer.length(); i++){
char guessAChar = guess.charAt(i);
char ansAChar = answer.charAt(i);
if(guessAChar == ansAChar){
aCount++;
}
}
for (int indexOfGuess = 0; indexOfGuess < answer.length(); indexOfGuess++)
{
for (int indexOfActualNumber = 0; indexOfActualNumber < answer.length(); indexOfActualNumber++)
{
if (guess.charAt(indexOfGuess) == (answer.charAt(indexOfActualNumber)))
{
bCount++;
}
}
}
bCount = bCount - aCount;
hintString =("Your hint is: \n"+aCount+"A" + bCount + "B");
return hintString;
}
}
EDIT: This problem has been solved: This method now searches and outputs how many numbers in each string match, and how many in each position are the same!
Variable bCount is the amount of numbers in the final string, but not in the right spot. You need a double loop for this to check each character in each string to see if they match. This might point you in the right direction.
int outer_counter = 0;
for(char g : guess.toCharArray())
{
int inner_counter = 0;
for(char a : answer.toCharArray())
{
if(g == a && inner_counter != outer_counter)
{
bCount++;
}
inner_counter++;
}
outer_counter++;
}
The counters make sure these are NOT in the same position.
So bCount is determining the number of digits that are in the answer, but not in the right place. So let's try this:
public string bCount()
{
for (int indexOfGuess = 0; indexOfGuess < answer.length(); indexOfGuess++)
{
for (int indexOfActualNumber = 0; indexOfActualNumber < answer.length(); indexOfActualNumber++)
{
if (guess.charAt(indexOfGuess).equals(answer.charAt(indexOfActualNumber))
{
bCount++;
}
}
}
}
This method does:
Creates an outer loop that loops through each index of the "guess" array
Creates an inner loop that, while the "guess" array is at an index, the inner loop will loop through each index (so while "guess" is at index 0, "answer" will go through all indexes before "guess" goes to 1, and then the inner loop runs again)
Check to see if the number at the guess index = number at the actual index.
If it is, increment bCount.
The only issue which I haven't taken care of for you is if the number is entered twice. Example: if the number is 1900, and you guess 1909, you number for bCount will be higher than it should be. However, I'll leave that to you as this is a homework assignment after all.