I am preparing for my exam from programming. And I am stuck on this task, I understand logic of patterns ( at least I think so ) but I can't figure out how to solve this.
Output for input a = 6 needs to be like :
012345
123456
234567
345678
456789
567890
Output for input a = 3 needs to be like :
012
123
234
Output for input a = 4 needs to be like :
0123
1234
2345
3456
But I'm getting this :
0 1 2 3 4 5
1 2 3 4 5
2 3 4 5
3 4 5
4 5
5
Here's my code:
for (int i = 0; i <= a; i++) {
for (int j = i; j < a; j++) {
System.out.print(j + " ");
}
System.out.println();
}
You need to make these changes to get the required output:
Termination conditions of the outer for loop should be i < a;
Termination conditions of the inner for loop should be j < a + i;
The number you're printing should be not j but j % 10 to satisfy the data sample you've provided (for input a=6 it prints 0 as the last number on the very last line instead of 10, that means we need not j, but only its rightmost digit which is the remainder of division by 10).
That's how it can be fixed:
public static void printNumbers(int a) {
for (int i = 0; i < a; i++) {
for (int j = i; j < a + i; j++) {
System.out.print(j % 10 + " ");
}
System.out.println();
}
}
Observations:
Since it is a 2 dimensional output, we will need 2 loops ( one inside the other ).
Also, the starting point for each line is the value from which the last line starts +1 .
If the value crosses 10, then we will keep the unit digit value only ( like in the last line). ( therefore we use modulus operator % that helps to extract the unit digit)
Code :
class Main {
public static void main(String[] args) {
int n = 6;
pattern(n);
}
private static void pattern(int n) {
int k = 0;
for (int i = 0; i < n; i++) {
for (int j = k; j < k + n; j++) {
System.out.print(j % 10);
}
k = i + 1;
System.out.println();
}
}
}
and the answer is :
012345
123456
234567
345678
456789
567890
this is my first "problem": Make a program to allow the user to input an integer value to be searched in list3. Your program should display whether the inputted integer value is found in list3, how many of it is in list3, and what are their locations in list3?"
It's almost done, the only problem is that I couldn't follow what is written output given in the example:
List1 : 1 3 2 5 7 8 5 6 9 4
List2 : 2 1 4 3 2 1 4 2 0 2
List3 : 3 4 6 8 9 9 9 8 9 6
Input value to search in List3: 9
The value 9 is in List3!
There are 4 of it in List3.
Located at: list3[4], list3[5], list3[6], list3[8]
and this is my output:
list1 : 1 3 2 5 7 8 5 6 9 4
list2 : 2 1 4 3 2 1 4 2 0 2
list3 : 3 4 6 8 9 9 9 8 9 6
Input value to search in List3: 9
The value 9 is in List3!
There are 4 of it in List 3.
Located at: 4
how do i display the "located at: " like in the example?
EDITED
Sorry, I'm kinda new here and in Programming. This is my code:
import java.util.ArrayList;
import java.util.Scanner;
public class List2Sample
{
public static void main(String[] args)
{
int list1[] = new int[10];
int list2[] = new int[10];
int list3[] = new int[10];
String input = "";
int i, x, num = 0, count = 0;
boolean found = false;
ArrayList<Integer> arr = new ArrayList<Integer>(10);
Scanner in = new Scanner(System.in);
for(i = 0; i < 10; i++)
{
list1[i] = 0;
}
for(i = 0; i < 10; i++)
{
System.out.print("List 1 [" + i + "] : ");
try
{
list1[i] = in.nextInt();
}
catch(Exception e)
{
System.out.println("Error!");
}
}
for(i = 0; i < 10; i++)
{
list2[i] = 0;
}
for(i = 0; i < 10; i++)
{
System.out.print("List 2 [" + i + "] : ");
try
{
list2[i] = in.nextInt();
}
catch(Exception e)
{
System.out.println("Error!");
}
}
System.out.print("list1 : ");
for(i = 0; i < 10; i++)
{
System.out.print(list1[i] + "\t");
}
System.out.println();
System.out.print("list2 : ");
for(i = 0; i < 10; i++)
{
System.out.print(list2[i] + "\t");
}
System.out.println();
System.out.print("list3 : ");
for(i = 0; i < 10; i++)
{
list3[0] = list1[0] + list2[0]; list3[1] = list1[1] + list2[1]; list3[2] = list1[2] + list2[2];
list3[3] = list1[3] + list2[3]; list3[4] = list1[4] + list2[4]; list3[5] = list1[5] + list2[5];
list3[6] = list1[6] + list2[6]; list3[7] = list1[7] + list2[7]; list3[8] = list1[8] + list2[8];
list3[9] = list1[9] + list2[9];
System.out.print(list3[i] + "\t");
}
System.out.println();
System.out.print("Input value to search in List3: ");
x = in.nextInt();
arr.add(list3[0]);
arr.add(list3[1]);
arr.add(list3[2]);
arr.add(list3[3]);
arr.add(list3[4]);
arr.add(list3[5]);
arr.add(list3[6]);
arr.add(list3[7]);
arr.add(list3[8]);
arr.add(list3[9]);
for (int n : list3)
{
if (n == x)
{
found = true;
break;
}
}
for (i = 0; i < 10; i++)
{
if (list3[i] == x)
{
count++;
}
}
for (Integer value : arr)
{}
int pos = arr.indexOf(x);
if(found)
System.out.println("The value " + x + " is in List3!");
else
System.out.println("The value " + x + " is in List3!");
System.out.println("There are " + count + " of it in List 3.");
System.out.println("Located at: " + pos);
}
}
Assuming list3 is an list of integers then using java8 streams
String locations=IntStream.range(0,list3.size())
.filter(i->list3.get(i)==userInput)
.map(index->"list3["+index+"]")
.collect(Collectors.joining(","));
Int occurences=locations.split(","). length;
if(occurences>0){System.out.println(userInput +"occurred" + occurences +" Times +" at locations "+locations);}
else{System.out.println(userInput +"Was not found");}
indexOf(ch) will only return the first appearance of the value in the array, if you want, you could supplement a second parameter to tell Java where to start looking for the character, like this: indexOf(ch, fromIndex).
However, in your case, it's much easier to just use an index based loop to loop through all elements in the array, then record the positions if you found matching characters, like this:
for(int i = 0; i < arr.length; i++){ // loop through all indices of the array, starting from 0, end at arr.length - 1
if(arr[i] == ch){ // arr[i] is each character in the array at index i, ch is the target character you're matching against
System.out.println("Character found at position " + i);
}
}
I had one leetcode challenge, details are below.
Check If Array Pairs Are Divisible by k
Given an array of integers arr of even length n and an integer k.
We want to divide the array into exactly n / 2 pairs such that the sum of each pair is divisible by k.
Return True If you can find a way to do that or False otherwise.
Example 1:
Input: arr = [1,2,3,4,5,10,6,7,8,9], k = 5
Output: true
Explanation: Pairs are (1,9),(2,8),(3,7),(4,6) and (5,10).
Example 2:
Input: arr = [1,2,3,4,5,6], k = 7
Output: true
Explanation: Pairs are (1,6),(2,5) and(3,4).
Example 3:
Input: arr = [1,2,3,4,5,6], k = 10
Output: false
Explanation: You can try all possible pairs to see that there is no way to divide arr into 3 pairs each with sum divisible by 10.
Example 4:
Input: arr = [-10,10], k = 2
Output: true
Example 5:
Input: arr = [-1,1,-2,2,-3,3,-4,4], k = 3
Output: true
Constraints:
arr.length == n
1 <= n <= 10^5
n is even.
-10^9 <= arr[i] <= 10^9
1 <= k <= 10^5
Some basic use case above to evaluate the result.
My Implementation
import java.util.ArrayList;
class Solution {
public static boolean canArrange (int[]arr, int k)
{
if(arr.length % 2 != 0){
return false;
}
int pairs = arr.length / 2;
int[] firstPair = new int[pairs];
int[] secondPair = new int[pairs];
int n =0;
for(int i=0; i<arr.length;i++){
if(i < pairs){
firstPair[i] = arr[i];
}else{
secondPair[n] = arr[i];
n++;
}
}
System.out.println ("pairs =" + pairs);
int divisablePairs = 0;
ArrayList<Integer> firstElement = new ArrayList();
ArrayList<Integer> secondElement = new ArrayList();
for (int i = 0; i < firstPair.length; i++)
{
for (int j = 0; j < secondPair.length; j++)
{
if ((firstPair[i] + secondPair[j]) % k == 0 && (firstPair[i] + secondPair[j]) >= 0)
{
firstElement.add(firstPair[i]);
secondElement.add(secondPair[j]);
System.out.println ("(" + firstPair[i] + "," + secondPair[j] + ")");
divisablePairs++;
}
}
}
return divisablePairs > 0 ? true : false;
}
}
Here one particular use case is getting failed but I am not sure why. Use case give below.
Input:
Array - [9606,4830,4037,-1054,3308,6966,6528,3953,473,-388,9878,-3797,2598,-3283,5813,-6446,-3625,-107,-8756,-3053,-2131,6609,4192,7408,1115,7456,-5674,1219,-8548,540,-9630,-4858,-2453,-726,9902,6192,-7996,1459,-1980,4285,-2659,4156,-2303,-855]
K - 10
My Output:
true
Expected:
false
Someone explain what is the issue with my implementation?
Here we can use an integer map of k size.
This'll pass through:
public class Solution {
public static boolean canArrange(int[] arr, int k) {
int[] countMapRemainders = new int[k];
for (int a : arr) {
int remainder = a % k;
if (remainder < 0) {
remainder += k;
}
countMapRemainders[remainder]++;
}
for (int i = 1; i < k; i++) {
if (countMapRemainders[i] != countMapRemainders[k - i]) {
return false;
}
}
return countMapRemainders[0] % 2 == 0;
}
}
Inputs:
[1,2,3,4,5,10,6,7,8,9]
5
[9606,4830,4037,-1054,3308,6966,6528,3953,473,-388,9878,-3797,2598,-3283,5813,-6446,-3625,-107,-8756,-3053,-2131,6609,4192,7408,1115,7456,-5674,1219,-8548,540,-9630,-4858,-2453,-726,9902,6192,-7996,1459,-1980,4285,-2659,4156,-2303,-855]
10
Outputs:
true
false
References
For additional details, you can see the Discussion Board. There are plenty of accepted solutions with a variety of languages and explanations, efficient algorithms, as well as asymptotic time/space complexity analysis1, 2 in there.
I have found a way for zigzag matrix but I am willing to find same as clean code for triangle pattern.
Example:
input = 3
Output:
1
32
456
I already coded a numbered matrix code here:
int k=0;
int t=1;
int n=4;
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
k+=t;
System.out.print(k);
}
k=k+n+t;
t=-t;
System.out.println();
}
Output:
1234
8765
9101112
16151413
int n = 6;
int num = 0;
int step = 1;
for (int i = 1; i <= n; i++) {
// num : (i² - i + 2)/2 .. same + i - 1
for (int j = 0; j < i; j++) {
num += step;
System.out.print(num);
System.out.print(' ');
}
num += i + (1 + 3*step)/2;
step = -step; // zig resp. zag
System.out.println();
}
Helpful was numbering i as row with exactly i elements.
Yielding
1
3 2
4 5 6
10 9 8 7
11 12 13 14 15
21 20 19 18 17 16
The problem was that every row i of i numbers has a lowest value (i² - i + 2)/2,
and for the next zigzagging number one needs to consider the following step.
From the last row number to the first row number of the next line has two cases:
step -1
step 1
Both formulas of both cases can be unified by the step.
step i num
+ 1 1 -> 4 += i + 2
- 2 2 -> 3 += i - 1
+ 3 6 -> 11 += i + 2
- 4 7 -> 10 += i - 1
The following will work:
public static void zigZag(int rows) {
int current = 1;
int increment = 1;
for (int row = 1; row <= rows; row++) {
int width = row + current;
for (int element = current; element < width; element++) {
System.out.print(current);
current+=increment;
}
System.out.println();
current += row + 0.5 - (0.5*increment);
increment = -increment;
}
}
Edit: just a note because I suspect your question might be homework motivated, so it might help if you can understand what's going on instead of just copy-pasting.
All that really needed to change was to use the external loop variable (the one that was originally creating your matrix square, which I've called row) in the inner loop which prints the individual elements of the row.
This is then used to calculate the first element of the next row. The increment value does the same as it does in your original, but now it can also be used to have the zig-zag pattern go up in integers other than 1.
Starting from the top of the triangle (1) will be row 1, all subsequent even rows are printed in reverse. Knowing that you can try something like this:
public class StackOverflow {
public static void main(String[] args) {
int triangleSize = 5;
int counter = 1;
int rowSize = 1;
for (int i = 1; i <= triangleSize; i++) {
if (i % 2 == 0) {
// Reverse number sequence
int reverseCounter = counter + rowSize - 1;
for (int j = 0; j < rowSize; j++) {
System.out.print(reverseCounter--);
counter++;
}
} else {
for (int j = 0; j < rowSize; j++) {
System.out.print(counter++);
}
}
System.out.println("");
rowSize++;
}
}
}
Keep track what row you're on (rowSize) and what value you're on (counter). When you're on an even row you have to start with the highest value that row will have and count backwards from it, but still increment your normal counter (int reverseCounter = counter + rowSize + 1).
Result:
1
32
456
10987
1112131415
Try this I coded it for you:
public class TriangleNum{
public static void main(String[] args) {
getTringle(5);
}
public static void getTringle(int j){
for (int i =0; i<j;i++) {
System.out.print(i+ "\r" );
for (int k =0; k<i;k++) {
System.out.print(k+ "\t" );
}
}
}
}
//Using C Language
#include<stdio.h>
int main(){
int n,count=1,k=1;
printf("Enter number of lines:\n");
scanf("%d",&n);
for(int i=1;i<=n;i++){
for(int j=1;j<=i;j++){
if(i%2==1){printf("%d",count);count++;}
else{printf("%d",count);count--;}}
count=count+k;
if(i%2==1){k=k+2;}
printf("\n");
}
return 0;
}
I'm writing a program to calculate the Hamming code, and I receive an array out of bounds exception. The issue seems to be with this method:
static int[] computeParityBits(int[] inWord, int[] parityBits) {
for (int i=0, m=2; m < inWord.length; i++) {
m = (int) Math.pow(m, i);
parityBits[i] = processPower(m, inWord);
}
return parityBits;
The integer m does not change it's value when using the Math.pow function on it. I've tried different things but I can't seem to make it work properly. The method is supposed to go through all powers of 2 as long as their value is lower than int[] inWord.length. After this it should assign parityBits[i] the value returned by the method processPower().
The exception received:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5
at hamming_code.HammingCoder.computeParityBits(HammingCoder.java:34)
at hamming_code.HammingCoder.computeHammingCode(HammingCoder.java:27)
at hamming_code.HammingCoder.main(HammingCoder.java:61)
A larger section of the code:
static int[] computeHammingCode(int[] inWord, int codeLength) {
int[] parityBits = new int[codeLength - inWord.length];
parityBits = computeParityBits(inWord, parityBits);
return parityBits;
}
static int[] computeParityBits(int[] inWord, int[] parityBits) {
for (int i=0, m=2; m < inWord.length; i++) {
m = (int) Math.pow(m, i);
parityBits[i] = processPower(m, inWord);
}
return parityBits;
}
static int processPower(int m, int[] inWord) {
int counter = 0;
for (int i = 0; i < inWord.length; i++){
for (int n = 0; n < m; n++) {
counter = counter + inWord[i];
}
for (int k = 0; k < m; k++) {
i++;
}
}
if (counter % 2 == 0) {
return 0;
} else
return 1;
}
Error message indicates that it fails for i = 5, but your loop is conditioned on the value of m, so something is wrong with your loop.
Printing the value of i and m for each iteration up to i = 5 will show you the error:
for (int i=0, m=2; i <= 5; i++) {
m = (int) Math.pow(m, i);
System.out.println(i + ": " + m);
}
OUTPUT (Ideone)
0: 1
1: 1
2: 1
3: 1
4: 1
5: 1
As you can see, m is always 1.
That is because first iteration calculates:
i=0,m=2: 2⁰ = 1
i=1,m=1: 1¹ = 1
i=2,m=1: 1² = 1
i=3,m=1: 1³ = 1
i=4,m=1: 1⁴ = 1
i=5,m=1: 1⁵ = 1
Debugging your code should have easily shown you this, faster than getting answer here.
I see nothing to prevent i from exceeding codeLength - inWord.length. That would account for the exception.
You get error because on fist iteration you have Math.pow(m, 0); and it equals to 1. Then m always will be 1, because power of 1 always 1. So i is incremented, but m not. But exit loop conditional m < inWord.length.