I am trying to understanding the working of this array in a loop
for (int answer=0; answer<responses.length; answer++)
{
++frequency[responses[answer]]
}
Frequency is an array initialized in start as
int [] frequency = new int [6];
We also have responses as an array having values int[] responses= {1,2,3,4,4,4,4,4}
I am not understanding how this ++frequency[responses[answer]] works, it look to me nested array but how it will work ?
There is no nested arrays. You are just nesting two array access syntaxes.
To explain this code, we first need to know how will the answer variable change. From the for loop header, we can see that it starts from 0, and goes all the way up to responses.length - 1, which is 8. Now we can evaluate the expression frequency[responses[answer]]:
// in each iteration of the loop
frequency[responses[0]]
frequency[responses[1]]
frequency[responses[2]]
frequency[responses[3]]
frequency[responses[4]]
frequency[responses[5]]
frequency[responses[6]]
frequency[responses[7]]
Now we can evaluate the responses[x] part. We just need to find the corresponding response in the responses array. responses[0] is the first item, which is 1.
frequency[1]
frequency[2]
frequency[3]
frequency[4]
frequency[4]
frequency[4]
frequency[4]
frequency[4]
The statement also includes the ++ operator, which increments that particular index of frequency by 1. So all of the above indices will be incremented by 1 one after another, making the frequency array look like this:
[0, 1, 1, 1, 5, 0]
On a higher level of abstraction, this code is counting how many times a particular response appears in the responses array. For example, 4 appeared 5 times.
The expession
++frequency[responses[answer]]
is exactly the same as if it had been written
int fi = responses[answer];
++frequency[fi];
frequency has six elements, and all the entries in responses are valid indices for a six-element array. answers has eight elements, so as long as answer is between 0 and 7, the whole thing will work.
Related
Given int[] arr = [7, 2, 5, 2]; and int index;, how can I use a for loop to make sure that index is assigned to 1 (the first index at which 2 was observed in arr) and not 3 (the last index at which 2 was observed in arr)?
I'm thinking using a break; statement but I'm not sure how to implement the syntax.
You can add every array value to a hashmap with the value as key and the index as value, that way if a key already exists you know at which index it was.
Alternatively you could also have the hashmap value be a list so you can store for each value, all of the indexes in which is appears in the array.
If you're using embedded for loops (the suggested answer when you search this question) one of your loop counters will point to the first instance while the second will point to the second instance. Just use the correct variable.
You can break a for loop once you've found what you want, like this:
for (int i = 0; i < arr.length; i++) {
if (foundDuplicate()) {
break;
}
}
// You end up here after the break
This gets you out of the for loop
You can also find the duplicate whichever way you want and then iterate over the array until you find the first instance.
Depends on what arbitrary rules have been placed on this exercise
I'm having trouble wrapping my head around how to implement a method that starts with an int[][] input and a predefined sum value that returns an int[][] output that only displays the adjacent values in the row that add up to the sum. For example, if the input array was
int[][] input = new int[][]{
{3,4,4,2,7},
{2,3,2,8,6},
{1,4,2,1,2}
}
when the sum is set to 7, it would yield an output array with the following values
{3,4,0,0,7},
{2,3,2,0,0},
{1,4,2,1,0}
}
The output array should only display values that add up to a set number (7) with their neighbors, or if its a number from 0-9 values that are the desired sum (when you search for 7 it displays all 7s). To further clarify, as you can see in the output array, it displays the first two values, 3 and 4, because they add to 7. It displays 2,3,2 because they also add to 7. It prints out 1,4,2,1 on the bottom because 1,4,2 add to 7 and 4,2,1 add to 7. To summarize, it displays only values which are 7 or add up to 7 with the numbers next to them, and otherwise displays 0. Also the input values must be <0.
After brainstorming for a while I know that the code will need a number of nested loops: one to loop through the rows, inside that one to loop through the columns, inside that a loop to update the sum which stops when the sum equals the preset sum (7 in this case), and finally a loop to update the output[][]. However, I'm having a great deal of trouble on writing code that implements all of these loops correctly. I am planning on doing the same thing with numbers that add up vertically, but want to focus on horizontal as of now.
This can be done in O(NxM) complexity.
For each row, you keep two indexes (say, iLow and iHigh initialised to the first item input [i][0]) and a sumSoFar variable. At each iteration, if the sumSoFar < 7 you increment iHigh. If it is > 7 then you increment iLow and iHigh. If It is == 7 then you've found one combination + increment iLow and iHigh.
This should give the high-level idea of the algorithm and I'm sure that a lot of details are missing/incomplete but you should be able to put that in code.
You need three nested loops. Or really, three levels of nested loops with two loops after each other on the innermost level, but I will return to that in the end.
Before any loops, create the backbone of your result array. It’s OK if it’s an array of null references to arrays at this point.
Outer loop: loop through the outer array. A classical for loop is one option. For each entry, create an inner array of the correct length in the result, filled with zeroes for a start.
Middle loop, loop through the entries in the inner array. Again a classical for loop is fine. Your goal is that each iteration will determine if a series of adjacent values with the sum 7 begins at this entry, and if so, find out how long it is, and copy the entries in question to the result array.
Inner loop (first inner loop, that is) is for adding adjacent entries to find out if the sum is 7. You start from the entry from the middle loop and add up the values. This loop has a double stop condition: you stop when the sum is 7 or greater (assuming all values are positive), but obviously you also stop when reaching the end of the inner array. A while loop would be for my taste. Only if the sum hits exactly 7, do you use a new inner loop to copy the values to the result.
PS If you assume all values are positive, you shouldn’t just assume, you should check. In the middle loop, if the value in that entry is 0 or negative, throw an IllegalArgumentException.
ArrayList<ArrayList<ArrayList<String>>> one = new ArrayList<ArrayList<ArrayList<String>>>();
one would look something like this with some example values:
[
[
["A","B","C",...],
["G","E","J",...],
...
],
[
["1","2",...],
["8","5","12","7",...],
...
],
...
]
Assuming that there will always be one base case, at least one letter arraylist (e.g. ["A","B","C"]), but there could be more (e.g. ["X,"Y","Z"]) and there may be any size of number arraylists, maybe none at all, but could be hundreds (e.g. ["1","2","3"],...,["997","998","999"]). Also, there could be more types of arraylists (e.g. ["#","#","$"]) of any size. So really the only thing that is definitive is that ALWAYS:
one.size()>=1
one.get(0).size()>=1
one.get(0).get(0).size()>=1
So the problem is: How can I best get every combination of each category without knowing how large each arraylist will be or having any repeats but assuming that one.get(0).get(0) is valid? e.g. ["A","B","C",...] ["1","2",...] ..., ["A","B","C",...] ["8","5","12","7",...] .... I'm using Java in my project currently but an any algorithm that works I can convert over myself. I apologize if this is not clear, I'm having a hard time putting it into words which is probably part of why I can't think of a solution.
I know two solutions to this, the recursive and the non recursive. Here's the non recursive (similar to the answer at How to get 2D array possible combinations )
1) Multiply the length of every array together. This is the number of possible combinations you can make. Call this totalcombinations.
2) Set up an int[] array called counters. It should be as long as the number of arrays, and all initialized to 0.
3a) For totalcombinations times, concatenate counter[0]th entry in arrays[0], the counter[1]th entry in arrays[1]... etc and add it to the list of all results.
3b) Then set j = 0 and increment counters[j]. If this causes counters[j] > arrays[j].length, then counters[j] = 0, ++j and increment the new counters[j] (e.g. repeat 3b)) until you do not get such an overflow.
If you imagine counters as being like the tumblers of a suitcase - when you overflow the first digit from 9 to 0, the next one ticks over - then you should get the strategy here.
I'm planning to do a small program that'll display a graph which will be updated a few times per second (maybe 100/200ms or so). The purpose is to plot over 1000 different values in the graph, somewhat like an XY plot.
When the array contains 1000 elements, I'd like to add a new element at the end, and in the process pushing all the other elements one step back. In essence, element 999 would become 998, and 998 would become 997... all the way to the first element, which would simply be thrown away. Does anyone have an example or a good algorithm for doing this, either with regular arrays, Vector, LinkedList or any other method?
My first thought would be to create a new array and copy the elements that I want to keep into the new one, throwing away say the first 100 elements. At this point, I'd add the new 100 elements at the end of the array, and keep repeating this process, but surely there must be a better way of doing this?
What you are asking about is called deque in the algorithmic world, i.e. double ended vector.
That is the class you will need.
Basically deque supports adding and removing elements from both the beginning and the end of the sequence.
EDIT Actually as I read through the documentation I was surprised to see that the sdk implementation of deque does not support direct indexing (I am used to using this structure in C++). So I kept on searching and found this answer, linking to this library, which might be of help for you.
Don't use an Array, the complexity of moving all elements is awful! The Java data structure that's best suited for this task is a Deque, I'd say.
I would keep on reusing the same array, and just restart at the beginning. To make myself more clear, suppose you have your array with elements 1..1000
int[] array = new int[1000];
...
array = {1, 2, ...., 1000 };
If you now have to add element 1001, instead of trying to have an array {2, 3, ..., 1000, 1001}, I would go for an array {1001, 2, 3, ... 1000} and just keep track at which index my array actually starts. This replaces the difficulty of moving all elements by keeping a simple counter to the begin-index. To make it easy for yourself, you can introduce a utility method
private int startIndex = 1;//0 at the start
//I assume we are in the situation with array {1001, 2, 3, ..., 1000 }
public int convertIndex( int index ){
return (index + startIndex) % 1000;
}
So here I am with this simple question
Consider these two for cycles and please
explain to me if there's any difference
between the two ways of writing
method 1 :
for(i=(max-1) ; i>=0 ; i--){ do-some-stuff }
method 2 :
for(i=max ; i>0 ; i--) { do-some-stuff }
the reason I'm asking this is because today at school
while we were seeing some Java functions, there was
this palindrome method wich would use as max the
length of the word passed to it and the method used
to cycle trough the for was the first, can anyone
clarify me why the person who writed that piece of
code prefeered using that method ?
Yes, there's a big difference - in the version, the range is [0, max-1]. In the second version, it's [1, max]. If you're trying to access a 0-based array with max elements, for example, the second version will blow up and the first won't.
If the order in which the loop ran didn't matter, I'd personally use the more idiomatic ascending sequence:
for (int i = 0; i < max; i++)
... but when descending, the first form gives the same range of values as this, just in the opposite order.
Both the loops will iterate max times. But the ranges would be different:
First loop's range would be max - 1 to 0 (both inclusive)
Second second loop's range would be max to 1.
Therefore, if you are using i as an array index, or doing some work which is a function of i , dependent of i, then it will create problems for the terminal values (for example 0 is considered in the first one, where as not by the second one). But if you simply want to iterate the loop max nos of times , and do some work which is independent of the value of i, then there is no difference.