Repeat an integer n times - java

I'm trying to make a pyramid out of an integer.
I.E the number 3 :
3
33
333
So based on the answers i found i made this :
int n = 8;
String n2 = Integer.toString(n);
for (int i=0; i<n; i++) {
System.out.println(StringUtils.repeat(n2, i));
}
But it's not working and would be suboptimal. Is there a simple way to repeat an integer n times in the same line ?
EDIT : made myself a method.. not quite happy either but it seems i can't just use something like System.out.println(int x, int n times)
int n = 8;
for (int i=0; i<=n; i++) {
for (int j=0; j<i; j++) {
System.out.print(n + " ");
}
System.out.println("");
}

Ok, you can do this without explicit loops using Java-8 streams:
IntStream.range(1,n).forEach(i -> System.out.println(StringUtils.repeat(n2, i));
or even without apache-commons:
IntStream.range(0,n).forEach(i -> System.out.println(String.join("", Collections.nCopies(i+1, n2))));
But in any case internally all these methods use loops.

I mean isn't it suboptimal to convert my int into a string ? AIn't
there a direct way to deal with the integer ? –
If you dont want to convert int to string.
This may help you.
int n = 3;
for (int i=1; i<=n; i++) {
System.out.println(new String(new char[i]).replace("\0", n+""));
}

Something as below.
public class Test{
public static String repeat(String str, int times) {
return new String(new char[times]).replace("\0", str);
}
public static void main(String[] args) {
for (int i = 1; i < 5; i++) {
System.out.println(repeat("3", i));
}
}
}
Output
3
33
333
3333

You could try to use a StringBuilder.
You would still have to loop, but it might be slightly better performance-wise.
int n = 8;
String n2 = Integer.toString(n);
StringBuilder builder = new StringBuilder(n);
for(int i = 0; i < n; i++) {
builder.append(n2);
System.out.println(builder.toString());
}
This does what you want, but not in the way you think about it. Instead of repeatedly having to create the repeating integer string, we simply build ONE string, saving us the work of repeating it.
To actually answer your question, you could use this code, although I would recomend the first approach:
char[] str = new char[n];
Arrays.fill(str, (char)(number + '0'));
new String(str);
This would only work if your integer is 0 <= number < 10.

To keep with integers, you may store last value each time, and add the next part :
i = 0 --> you get 3
i = 1 --> you get 33 (i0 + 30)
i = 2 --> you get 333 (i1 + 300)
int lastValue = 0;
for (int i=0; i<=n; i++) {
int currentValue = lastValue + (n * Math.pow(10, i));
System.out.println(currentValue);
lastValue = currentValue ;
}
This obviously works for one-digit integers only.

Related

Trying to get a loop to work through alternate arrays

I'm trying to print out a string by alternating its letter cases. I want YourString to come out as YoUrStRiNg. I've tried three things but I can't get the loop to work the way I need it to. Here's what I have so far:
//one attempt
String s = "yourString";
String x = "";
for (int i = 0; i < s.length(); i += 2) {
for (int j = 1; j < s.length(); j += 2) {
x += Character.toUpperCase(s.charAt(i));
x += Character.toLowerCase(s.charAt(j));
}
}
System.out.println(x);
//the desired result but not the ideal solution
String[] sArray = {"Your", "String"};
String f = "";
for (String n : sArray) {
f += n;
}
char[] c = f.toUpperCase().toCharArray();
char[] d = f.toLowerCase().toCharArray();
System.out.print(c[0]);
System.out.print(d[1]);
System.out.print(c[2]);
System.out.print(d[3]);
System.out.print(c[4]);
System.out.print(d[5]);
System.out.print(c[6]);
System.out.print(d[7]);
System.out.print(c[8]);
System.out.print(d[9]);
System.out.println();
//third attempt with loop but the first loop keeps starting from zero
String t = "";
for (int i = 0; i < c.length; i += 2) {
for (int j = 1; j < d.length; j += 2) {
t += Character.toUpperCase(c[i]);
t += Character.toLowerCase(d[j]);
}
System.out.print(t);
}
What am I doing wrong?
Actually, there's no need to iterate more than once through the elements of the String. As you need to change the case of the character alternatively, you can just count the position of your iteration, by using the operator %. So, for example, given c as the current String character, the operation would be like this:
System.out.print(i % 2 == 0, (char)Character.toUpperCase(c) : (char)Character.toLowerCase(c));
However, you can actually take advantages from Java Stream and lambda expression, so to realize a very elegant solution for that.
I am going to show you my proposal solution. The only issue is that you cannot actually have a proper cycle variable, as the variable you access inside the lamba expression must be final or effective final, so I used a sort of trick for it.
That is just to give you an idea, you can actually personalize, make it reusable, and improve it as you wish:
public class MyStringTest {
public static void main(String args[]) {
String s = "yourString";
initializeCycleVariable();
s.chars().forEach(c ->
{System.out.print( MyStringTest.getAndIncrement() %2 == 0 ?
(char)Character.toUpperCase(c) :
(char)Character.toLowerCase(c));
});
}
private static int i = 0;
public initializeCycleVariable() { i = 0; }
public static int getAndIncrement() { return i++; }
}
And here is the output:
YoUrStRiNg
You should iterate over the string char by char. You could do upper case for the even indexes, and lower case for the odd ones. Sorry for not providing more detail, but it is clear that this is an assignment.
Try this one out,
String s = "yourString", x = "";
for(int i = 0; i < str.length(); i++){
if(i % 2 == 0)
x += Character.toUpperCase(s.charAt(i));
else
x += Character.toLowerCase(s.charAt(i));
}
System.out.println(x);

Stopping a for loop without using break

I'm trying to write a program that prints all substrings of entered string. For example if user enter "rum" the output will be this:
r
u
m
ru
um
rum
import java.util.Scanner;
public class AllSubStrings
{
public static void main(String[]args)
{
Scanner in = new Scanner(System.in);
System.out.print("Enter a string: ");
String str = in.next();
String sub = "";
for(int i=0; i<str.length(); i++)
{
for(int a=0; a<str.length() ; a++)
{
if(i+a+1>str.length())break;
sub = str.substring(a,i+a+1);
System.out.println(sub);
}
}
}
}
This program works perfectly but since we didn't learn how to use "break" in classes, i'm looking for something different. Any idea apart from "break" are welcome.
Thanks in advance.
You can use this while loop cycle instead of for:
int a = 0;
while (a < str.length && i + a < str.length()) {
sub = str.substring(a, i + a + 1);
System.out.println(sub);
a++;
}
Also it is possible to replace break with return statement
Calculate how many possible substrings there can be for a certain length. For example, length 1 = 1 substring, length 2 = 3, length 3 = 6, and so on.
Then loop for that many times. There should be a generic formula you can use for no matter how long of an input string.
You don't need a break to do this task.
int len = str.length();
for (int i = 0; i < len; i++) {
for (int j = i; j < len; j++) {
System.out.println( str.substring( i, j + 1 ) );
}
}
You can have two conditions in the for loop
for(int a = 0; a < str.length() && i + a < str.length(); a++)
{
sub = str.substring(a,i+a+1);
System.out.println(sub);
}
Note that i + a + 1 <= str.length() is the same as i + a < str.length()

Calculate factorial of 50 using array only in java

I'm a total beginner of java.
I have a homework to write a complete program that calculates the factorial of 50 using array.
I can't use any method like biginteger.
I can only use array because my professor wants us to understand the logic behind, I guess...
However, he didn't really teach us the detail of array, so I'm really confused here.
Basically, I'm trying to divide the big number and put it into array slot. So if the first array gets 235, I can divide it and extract the number and put it into one array slot. Then, put the remain next array slot. And repeat the process until I get the result (which is factorial of 50, and it's a huge number..)
I tried to understand what's the logic behind, but I really can't figure it out.. So far I have this on my mind.
import java.util.Scanner;
class Factorial
{
public static void main(String[] args)
{
int n;
Scanner kb = new Scanner(System.in);
System.out.println("Enter n");
n = kb.nextInt();
System.out.println(n +"! = " + fact(n));
}
public static int fact(int n)
{
int product = 1;
int[] a = new int[100];
a[0] = 1;
for (int j = 2; j < a.length; j++)
{
for(; n >= 1; n--)
{
product = product * n;
a[j-1] = n;
a[j] = a[j]/10;
a[j+1] = a[j]%10;
}
}
return product;
}
}
But it doesn't show me the factorial of 50.
it shows me 0 as the result, so apparently, it's not working.
I'm trying to use one method (fact()), but I'm not sure that's the right way to do.
My professor mentioned about using operator / and % to assign the number to the next slot of array repeatedly.
So I'm trying to use that for this homework.
Does anyone have an idea for this homework?
Please help me!
And sorry for the confusing instruction... I'm confused also, so please forgive me.
FYI: factorial of 50 is 30414093201713378043612608166064768844377641568960512000000000000
Try this.
static int[] fact(int n) {
int[] r = new int[100];
r[0] = 1;
for (int i = 1; i <= n; ++i) {
int carry = 0;
for (int j = 0; j < r.length; ++j) {
int x = r[j] * i + carry;
r[j] = x % 10;
carry = x / 10;
}
}
return r;
}
and
int[] result = fact(50);
int i = result.length - 1;
while (i > 0 && result[i] == 0)
--i;
while (i >= 0)
System.out.print(result[i--]);
System.out.println();
// -> 30414093201713378043612608166064768844377641568960512000000000000
Her's my result:
50 factorial - 30414093201713378043612608166064768844377641568960512000000000000
And here's the code. I hard coded an array of 100 digits. When printing, I skip the leading zeroes.
public class FactorialArray {
public static void main(String[] args) {
int n = 50;
System.out.print(n + " factorial - ");
int[] result = factorial(n);
boolean firstDigit = false;
for (int digit : result) {
if (digit > 0) {
firstDigit = true;
}
if (firstDigit) {
System.out.print(digit);
}
}
System.out.println();
}
private static int[] factorial(int n) {
int[] r = new int[100];
r[r.length - 1] = 1;
for (int i = 1; i <= n; i++) {
int carry = 0;
for (int j = r.length - 1; j >= 0; j--) {
int x = r[j] * i + carry;
r[j] = x % 10;
carry = x / 10;
}
}
return r;
}
}
How about:
public static BigInteger p(int numOfAllPerson) {
if (numOfAllPerson < 0) {
throw new IllegalArgumentException();
}
if (numOfAllPerson == 0) {
return BigInteger.ONE;
}
BigInteger retBigInt = BigInteger.ONE;
for (; numOfAllPerson > 0; numOfAllPerson--) {
retBigInt = retBigInt.multiply(BigInteger.valueOf(numOfAllPerson));
}
return retBigInt;
}
Please recall basic level of math how multiplication works?
2344
X 34
= (2344*4)*10^0 + (2344*3)*10^1 = ans
2344
X334
= (2344*4)*10^0 + (2344*3)*10^1 + (2344*3)*10^2= ans
So for m digits X n digits you need n list of string array.
Each time you multiply each digits with m. and store it.
After each step you will append 0,1,2,n-1 trailing zero(s) to that string.
Finally, sum all of n listed string. You know how to do that.
So up to this you know m*n
now it is very easy to compute 1*..........*49*50.
how about:
int[] arrayOfFifty = new int[50];
//populate the array with 1 to 50
for(int i = 1; i < 51; i++){
arrayOfFifty[i-1] = i;
}
//perform the factorial
long result = 1;
for(int i = 0; i < arrayOfFifty.length; i++){
result = arrayOfFifty[i] * result;
}
Did not test this. No idea how big the number is and if it would cause error due to the size of the number.
Updated. arrays use ".length" to measure the size.
I now updated result to long data type and it returns the following - which is obviously incorrect. This is a massive number and I'm not sure what your professor is trying to get at.
-3258495067890909184

How to sort array of numbers without gaps?

I have numbers like: 1,7,1,5 and I want to sort them without gaps between them (i.e.) 1,7,1,5 gets sorted to 1,1,2,3. (5 turns into 2; 7 turns into 3).
My code looks like this (works fine), but in some cases returns null pointer ex, or something like that :/
public void shake(Car[] c){
for(int i = 1; i < MaxPriority; i++)
if(!isCarWithPriority(i, c))
for(int j = i; j < 10; j++)
if(isCarWithPriority(j, c))
for(int k = 0; k < getCarsWithPriority(j, c).length; k++)
getCarsWithPriority(j, c)[k].setPriority(i);
}
Can you help me?
You can try iterating through the numbers after sorting them. subtract 1st from 2nd if result is 0 then dont do anything else replace 2nd by first + 1 then compare 3rd one in the same way with second.. keep on till last number. you will get the desired output. This can be achieved by a single loop in java.
This will do the trick
public static void main(String[] a) {
Integer [] arr = {1,7,1,5};
Arrays.sort(arr);
for (Integer integer : arr) {
System.out.println(integer);
}
for(int i=0; i< arr.length-1 ;i++){
if(arr[i+1]-arr[i] ==0){
continue;
}else{
arr[i+1] =arr[i]+1;
}
}
System.out.println("--------------------");
for (Integer integer : arr) {
System.out.println(integer);
}
}

Is there a better (faster) way to divide a number to digits?

I wrote this:
void blah(int num)
{
int numOfDigits = Math.log10(num);
int arr[] = new int[numOfDigits + 1];
for(int i = numOfDigits; i>0; i--)
{
arr[i] = num%10;
num = num/10;
}
}
But I thought there must be a more elegant way of doing this. Is there?
If you're happy with Strings, you could do this:
String[] arr = Integer.toString(num).split("(?<=\\d)");
If you want to go from this to int[]:
int[] arrint = new int[arr.length];
for (int i = 0; i < arr.length; i++)
arrint[i] = Integer.parseInt(arr[i]);
Consider converting the integer to a string using Integer.toString and then using string.toCharArray() and converting back. This may or may not be more 'elegant' depending on your worldview.
This might be one way (i am not super proud about this :))
Integer number = 1234567890; // input number
String temp = number.toString(); // convert to string
int [] output = new int[temp.length()];
for (int i=0 ; i< temp.length(); i++) // get character at index i from string
output[i] = temp.charAt(i) - '0'; // convert it to number by removing '0'

Categories