Looping though an array in java spliting the elements - java

So I have an array in java that looks like this:
int[] theArray = {2,3,6,9,10,12,17,16,18,20,23,24,28,30,31};
Desired output:
2 3 6 9 10
12 17 16 18 20
23 24 28 30 31

for(int i =0;i<theArray.length;i++)
{
if(i%5==0 && i!=0)
{System.out.println();
}
System.out.print(theArray[i]+" ");
}

All you have to do is go through the array one by one, and use System.out.print to print the elements for each set of 5 elements. Once you have printed 5 elements, do a system.out.println("");

So, basically you want to output the values in an array with a newline after every fifth element? You can use the modulo operator to achieve that.
In (untested) code:
for (int i = 0; i < arrayWithNumbers.length; i++)
{
if (i % 5 == 0 && i != 0) // end of the line
{
System.out.println(arrayWithNumbers[i]);
}
else
{
System.out.print(arrayWithNumbers[i]);
}
}

Related

Intuition behind using a two pointers approach

I am solving a question on LeetCode.com:
A string S of lowercase English letters is given. We want to partition this string into as many parts as possible so that each letter appears in at most one part, and return a list of integers representing the size of these parts.
For the input: "ababcbacadefegdehijhklij" the output is: [9,7,8]
A highly upvoted solution is as below:
public List<Integer> partitionLabels(String S) {
if(S == null || S.length() == 0){
return null;
}
List<Integer> list = new ArrayList<>();
int[] map = new int[26]; // record the last index of the each char
for(int i = 0; i < S.length(); i++){
map[S.charAt(i)-'a'] = i;
}
// record the end index of the current sub string
int last = 0;
int start = 0;
for(int i = 0; i < S.length(); i++){
last = Math.max(last, map[S.charAt(i)-'a']);
if(last == i){
list.add(last - start + 1);
start = last + 1;
}
}
return list;
}
I understand what we are doing in the first for loop (we just store the index of the last occurrence of a character), but I am not too sure about the second one:
a. Why do we calculate the max() and compare last==i?
b. How does it help us achieve what we seek - in the above example, when we encounter a at position 8 (0-indexed), what guarantees that we won't encounter, say b, at a position greater than 8? Because, if we do, then considering 8 as the end position of our substring is incorrect.
Thanks!
If we encounter a character S[i] we may cut the string only after it's last occurence, hence map[S.charAt(i)-'a']. We maximize the value in last because we need to ensure that all the processed characters will have their last occurence in the prefix, so we look at the rightmost of such indices, hence the max. If we encounter a character S[i] such that i is it's last occurrence and all characters before have their last occurrences before i, we may add the substring start..i to the result, and set start = i + 1 for the next substring.
The idea is this. Whenever the last occurrence of a particular character matches the current index, it means that this particular character appears only in this part.
To understand this better, just do this.
int last = 0;
int start = 0;
for(int i = 0; i < S.length(); i++){
last = Math.max(last, map[S.charAt(i)-'a']);
System.out.println(last+" "+i);
if(last == i){
list.add(last - start + 1);
start = last + 1;
}
}
Take your example string "ababcbacadefegdehijhklij".
Now, the output would be
8 0
8 1
8 2
8 3
8 4
8 5
8 6
8 7
8 8
14 9
15 10
15 11
15 12
15 13
15 14
15 15
19 16
22 17
23 18
23 19
23 20
23 21
23 22
23 23
The last occurrence of a is at the 8th position. Now we are at 0th position. Increment i. So, the till we get to 8th position, we cant be sure that each part contains at most 1 character. Suppose the next character is b and it occurs finally in 10th position, then we need to confirm till 10th position.
if(last == i){
}
The above if just confirms that the part is over and we can start a new part from the next index. Before doing this, we are adding the length of the current part to the output.

Processing the rows of a 2D array of ints

thanks in advance for your help. I'm new to java and I've been having difficulty processing the rows of a 2D array of ints. I've searched through this forum and other resourceful places, but nothing was helpful enough.
Here are the array elements:
1 2 3 4
4 9 17 26
2 4 6 8
1 3 5 7
9 12 32 33
4 8 10 16
3 7 9 21
10 11 12 13
here is my incorect code:
for (int row=0; row<list.length; row++) {
for (int col=0; col<list[row].length; col++) {
if (list[row][0] + 1 != list[row][1] &&
list[row][1] + 1 != list[row][2] &&
list[row][2] + 1 != list[row][3]) {
System.out.print(list[row][col] + " ");
}
}
System.out.println()
I need a code that can test and print the rows of the array whose elements are NOT consecutively incremented by 1, such as 1 2 3 4 and 10 11 12 13, assuming you do not know the values of the elements of the array.
You can iterate through the whole column, compare each value, and use a boolean to keep track if they're consecutively incremented or not. Something like this:
boolean rowIsConsecutive;
int previousValue;
for (int row = 0; row<list.length; row++)
{
rowIsConsecutive = true;
previousValue = list[row][0]; // This will blow up with a 1D array. Just wrote it like this for readability.
for (int col = 1; col<list[row].length && rowIsConsecutive; col++)
{
if (list[row][col] == previousValue + 1)
{
previousValue = list[row][col];
}
else
{
rowIsConsecutive = false;
}
}
if (rowIsConsecutive)
{
System.out.println(Arrays.toString(list[row]));
}
}
Disclaimer: I didn't test this, but something along these lines should work. And I leave it to you to come up with a more performant way to do it :)

Trying to create loop that fills array using info from another array + hash map

I'm trying to prepare data to be used inside of a histogram. I want 2 arrays, one is all the temperatures from my highest and lowest collected temperature. The second array will contain the frequency of each temperature.
int difference is the difference from the lowest and highest temp
Array temp contains the temperatures collected
HashMap map contains the frequencies collected of each temp
Array tempGaps contains the temperatures + every other temp that was not collected
Array finalTemps contains the frequency of each temp.
The goal I hope to achieve is two arrays, one with all the temperatures, one with the frequencies of each and their index value is what corresponds them to eachother.
public void fillGaps() {
int j = 0;
tempGaps = new int[difference];
finalTemps = new int[difference];
for (int i = 0; i < difference; i++) {
tempGaps[i] = temp[0] + i;
if (tempGaps[i] == temp[j]) {
finalTemps[i] = map.get(new Integer(tempGaps[i]));
j++;
} else {
finalTemps[i] = 0;
}
}
}output: https://pastebin.com/nFCZXFyp
Output:
7 ->1 9 ->1 10 ->1 12 ->1 14 ->2 15 ->1 16 ->1 18 ->2 19 ->1 21 ->1
TEMP GAPS
7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
FINAL TEMPS
1 0 1 1 0 1 0 2 0 0 0 0 0 0 0
My finalTemp output stops after 14 degrees - occurs 2 times. It does this after any data set I put in which has a frequency of more than 1. Please help! Thanks!!
I don't believe you need the j variable. It seems to make things confusing, especially because the for loop is only a single pass-through. Instead, fetch the value from the map. If null, assign 0, otherwise, assign the value.
public void fillGaps() {
tempGaps = new int[difference];
finalTemps = new int[difference];
for (int i = 0; i < difference; i++) { //navigate through every temperature
tempGaps[i] = temp[0] + i; //assign the current temperature
Integer frequency = map.get(new Integer(tempGaps[i])); //fetch the frequency
finalTemps[i] = frequency == null ? 0 : frequency; //assign 0 if null, otherwise frequency if not null
}
}

Creating a sliding number puzzle board using arrays in Java

So I'm kind of new to Java and decided to create a sliding number puzzle of some sort. Here's what I have :
int[] puz = {1,2,3,
4,5,6,
7,8,9}
for(int i=0; i<puz.length; i++){
System.out.println(puz[i]);
}
The 1 is supposed to be the blank spot but I'll figure that out later. My problem is that the code prints:
1
2
3
4
5
6
7
8
9
when I want it to print:
1 2 3
4 5 6
7 8 9
I've also tried doing a nested loop that I'm too embarrassed to show on here due to how hideous it was.
Would I try using a 2d array instead?
I guess you could try...
int puz = {1,2,3,4,5,6,7,8,9};
int n = Math.ceil(Math.sqrt(puz.length));
for (int i = 0; i < puz.length; i++) {
System.out.print(puz[i] + ((i + 1) % n == 0 ? "\r\n" : " ");
}
Try creating a variable counter and increment it every time you iterate through the loop. Using a modulus operator, divide it by 3 and when remainder is 0, create a new line.
int puz = {1,2,3,4,5,6,7,8,9};
int counter = 1;
for(int i=0; i<puz.length; i++){
System.out.print(puz[i]);
if (counter % 3 == 0){
System.out.println("");
}
counter++;
}
The trick here is to use the modulus operator. This operator divides one number by another, and returns the remainder. In java (and everywhere else as far as I know), % is the modulus operator. If you want every third number to have a line break after it, simply divide by three using modulus division, like so:
int[] puz = {1,2,3,4,5,6,7,8,9};
//For what it's worth, you don't have this semicolon in your question, so I added it in.
for(int i=0; i<puz.length; i++){
System.out.print(puz[i] + " ");
if(i % 3 == 2){//It's equal to 2 because you start at 0 and not 1.
System.out.println("");
}
}
This code, when executed, prints the following, which is what you wanted:
1 2 3
4 5 6
7 8 9

Basic Java arrays - output

I have created an int array to hold 100 values and have initialized them to be random integer values from 1-100.
Now my task is to output this array in a 10x10 block separated by tabs.
for example:
48 49 88 ..... (until 10 numbers appear on this line)
45 1 55 ..... (until 10 numbers appear on this line)
59 21 11 ..... (until 10 numbers appear on this line)
until 10 numbers appear going down as well
I'm kind of lost on how to do this, any tips?
A for loop is the easiest way to do this. Assuming x is the name of your single-dimensional, 100-element int array:
for(int i = 0; i < x.length; ++i)
{
System.out.print(x[i]);
if((i % 10) == 9)
{
System.out.print("\n");
//or System.out.println();
//both print a new line
}
else
{
System.out.print("\t");
}
}
\t gives you a tab, \n gives you a new line.
The (i % 10) == 9 part checks to see if you are on the 10th column. If you are, then you create a new line with the \n character.
This will iterate to the end of the array as well and no further, so if you ended up having a different number of columns than 100, this would not run the risk of trying to access an element that does not exist.
What you have to do, is to put a a newline-sign "\n" after each 10th element and a tab "\t" after each other one
Let's say a is your array. Then you could accomplish this at example by doing:
for(int i = 1; i <= a.length; i++){
//print out the element at the i-th position
System.out.print(a[i-1])
//check, if
if(i % 10 == 0){
//you could also simply use System.out.println()
System.out.print("\n");
}else{
System.out.print("\t");
}
}
If you just want to print them in that maner. Use som form of while loop that prints out 10 elements with a tab between them and last element Will have a new line sign because of a If statement for 10th element. This van be done through some form of counter.

Categories

Resources