Let's say that I have the following number: 1286 now I want to remove the last digit 6 and end up with the first 3 digits 128 only. I also would like to do this using the number 6 and the number 1286 only as inputs.
Also if there is a c# solution would be great.
Thanks
Edit:
I want to do this using a math equation between the 6 and the 1286, I already know how to parse strings, which is not what I'm after.
please try the below code: (this is done only using mathematical functions, also I don't know C#)
java.util.Scanner s=new java.util.Scanner(System.in);
int last=s.nextInt();
int firstNumber=s.nextInt();
int ans=0;
loop:
for(int temp=firstNumber,i=0;temp>0;temp/=10)
{
if(temp%10==last){ans=temp/10;while(i>0){ans=ans*10+(i%10);i/=10;} break loop;}
i=i*10;
i=i+(temp%10);
}
if(ans>0)System.out.println(ans);
}
}
string input = "OneTwoThree";
// Get first three characters
string sub = input.Substring(0, 3);
sub will now have the first 3 chars from the string, the 0 is the start pos, and then how many chars do you want (ie: 3) - this is where the (0, 3) come in to it - if you had (3, 3), sub would equal "Two"
I think this might be what you are looking for :)
In JavaScript: Here is your number:
var num = 1286;
This line removes the last digit:
num % 10; //returns 6
And these two lines remove the 6:
num /= 10 // turns num to 128.6
num = Math.trunc(num) // num now equals 128
Better yet, you could put it in a function, like so:
function sumOfDigits(num) {
const sumArr = [];
while (num > 0) {
sumArr.push(num % 10);
num /= 10;
num = Math.trunc(num);
}
return sumArr.reduce((a, b) => a + b, 0);
}
sumOfDigits(1234);
// returns 10
Hope this helps.
Related
Given the following code which encodes a number - how can I calculate the maximum number if I want to limit the length of my generated keys. e.g. setting the max length of the result of encode(num) to some fixed value say 10
var alphabet = <SOME SET OF KEYS>,
base = alphabet.length;
this.encode = function(num) {
var str = '';
while (num > 0) {
str = _alphabet.charAt(num % base) + str;
num = Math.floor(num / base);
}
return str;
};
You are constructing num's representation in base base, with some arbitrary set of characters as numerals (alphabet).
For n characters we can represent numbers 0 through base^n - 1, so the answer to your question is base^10 - 1. For example, using the decimal system, with 5 digits we can represent numbers from 0 to 99999 (10^5 - 1).
It's worth noting that you will not ever use some sub-n length strings such as '001' or '0405' (using the decimal system numerals) - so any string starting with the equivalent of 0 except '0' itself.
I imagine that, for the purpose of a URL shortener that is allowed variable length, this might be considered a waste. By using all combinations you could represent numbers 0 through base^(n+1) - 2, but it wouldn't be as straightforward as your scheme.
I'm trying to improve my recursion skill(reading a written recursion function) by looking at examples. However, I can easily get the logic of recursions without local variables. In below example, I can't understand how the total variables work. How should I think a recursive function to read and write by using local variables? I'm thinking it like stack go-hit-back. By the way, I wrote the example without variables. I tried to write just countThrees(n / 10); instead of total = total + countThrees(n / 10); but it doesn't work.
with total variable:
int countThrees(int n) {
if (n == 0) { return 0; }
int lastDigit = n % 10;
int total = 0;
total = total + countThrees(n / 10);
if (lastDigit == 3) {
total = total + 1;
}
return total;
}
simplified version
int countThrees(int x)
{
if (x / 10 == 0) return 0;
if (x % 10 == 3)
return 1 + countThrees(x / 10);
return countThrees(x / 10);
}
In both case, you have to use a stack indeed, but when there are local variables, you need more space in the stack as you need to put every local variables inside. In all cases, the line number from where you jump in a new is also store.
So, in your second algorithme, if x = 13, the stack will store "line 4" in the first step, and "line 4; line 3" in the second one, in the third step you don't add anything to the stack because there is not new recursion call. At the end of this step, you read the stack (it's a First in, Last out stack) to know where you have to go and you remove "line 3" from the stack, and so.
In your first algorithme, the only difference is that you have to add the locale variable in the stack. So, at the end of the second step, it looks like "Total = 0, line 4; Total = 0, line 4".
I hope to be clear enough.
The first condition should read:
if (x == 0) return 0;
Otherwise the single 3 would yield 0.
And in functional style the entire code reduces to:
return x == 0 ? 0
: countThrees(x / 10) + (x % 10 == 3 ? 1 : 0);
On the local variables:
int countThrees(int n) {
if (n == 0) {
return 0;
}
// Let an alter ego do the other digits:
int total = countThrees(n / 10);
// Do this digit:
int lastDigit = n % 10;
if (lastDigit == 3) {
++total;
}
return total;
}
The original code was a bit undecided, when or what to do, like adding to total after having it initialized with 0.
By declaring the variable at the first usage, things become more clear.
For instance the absolute laziness: first letting the recursive instances calculate the total of the other digits, and only then doing the last digit oneself.
Using a variable lastDigit with only one usage is not wrong; it explains what is happening: you inspect the last digit.
Preincrement operator ++x; is x += 1; is x = x + 1;.
One could have done it (recursive call and own work) the other way around, so it probably says something about the writer's psychological preferences
The stack usage: yes total before the recursive call is an extra variable on the stack. Irrelevant for numbers. Also a smart compiler could see that total is a result.
On the usage of variables: they can be stateful, and hence are useful for turning recursion into iteration. For that tail recursion is easiest: the recursion happening last.
int countThrees(int n) {
int total = 0;
while (n != 0) {
int digit = n % 10;
if (digit == 3) {
++total;
}
n /= 10; // Divide by 10
}
return total;
}
I'm trying to write a basic function to take an integer and evaluate to a bool that will check whether the integer is a prime or not.
I've used an auxiliary function to keep track of the current divisor I'm testing, like so:
fun is_divisible(n : int, currentDivisor : int) =
if currentDivisor <= n - 1 then
n mod currentDivisor = 0 orelse is_divisible(n, currentDivisor + 1)
else
true;
fun is_prime(n : int) : bool =
if n = 2 then
true
else
not(is_divisible(n, 2));
It looks right to me but I test it on 9 and get false and then on 11 and get false as well.
Sorry for all the questions today and thanks!
The problem is that if your is_divisible reaches the last case it should return false because it means that all the iterated divisors have resulted in a remainder larger than zero except for the last one which is the number it self. So you should rename is_divisible and return false instead of true
I'm learning how to do recursion, and I want to make sure that I'm doing it correctly. I just finished a question on codingbat that reads like this:
Given a non-negative int n, return the count of the occurrences of 7
as a digit, so for example 717 yields 2. (no loops). Note that mod (%)
by 10 yields the rightmost digit (126 % 10 is 6), while divide (/) by
10 removes the rightmost digit (126 / 10 is 12).
count7(717) → 2
count7(7) → 1
count7(123) → 0
And my solution, which worked, looks like this:
public int count7(int n) {
int count = 0;
if(n < 7) {
return count;
} else {
int divided = n / 10;
if(n % 10 == 7) count++;
return count + count7(divided);
}
}
Even though my solution passed, I want to make sure that I'm working through these recursion problems correctly. Should I have a counter sitting outside the if/else statement? If not, why? If not, how would you solve it instead.
The more self-contained, the better - and your answer is self-contained. And it has the two requisites for correct recursion:
Provide a "stopper"
public int count7(int n) {
int count = 0;
if(n < 7) {
return count;
If n is less than 7, return 0, since n clearly contains no 7s.
Otherwise, assume the problem is solved for some smaller number
} else {
int divided = n / 10;
if(n % 10 == 7) count++;
return count + count7(divided);
}
}
Remove the rightmost digit and assume that the problem is solved for what's left. That's the recursion count7(divided). Meanwhile, what about that rightmost digit? If it is 7, that needs to go into our ultimate answer, so add it in.
So far, so good.
Critique
Your structure is misleading. count at the start actually does nothing. You could have written this:
public int count7(int n) {
if(n < 7) {
return 0;
In that case there is also no need for your count++. We will add 1 if this is a 7 and not if it isn't:
} else {
int divided = n / 10;
if(n % 10 == 7) return 1 + count7(divided);
return count7(divided);
}
}
Observe that that is your answer - but it is more "honest" than what you wrote. There was nothing wrong with how you were recursing, but the presentation, I'm suggesting, can be clearer and less crabbed. Your code should read like a verbal description of the approach you are taking: "If this number is less than 7, return 0. Otherwise, pull off the last digit and recurse on what's left, adding 1 only if the number we pulled off is a 7."
There are recursion problems where you might generate a "count" value of some sort and pass it into the recursion call, but this is not one of them. Thus the whole count variable thing is just a red herring.
We have:
n1 number of {} brackets ,
n2 number of () brackets ,
n3 number of [] brackets ,
How many different valid combination of these brackets we can have?
What I thought: I wrote a brute force code in java (which comes in the following) and counted all possible combinations, I know it's the worst solution possible,
(the code is for general case in which we can have different types of brackets)
Any mathematical approach ?
Note 1: valid combination is defined as usual, e.g. {{()}} : valid , {(}){} : invalid
Note 2: let's assume that we have 2 pairs of {} , 1 pair of () and 1 pair of [], the number of valid combinations would be 168 and the number of all possible (valid & invalid) combinations would be 840
static void paranthesis_combination(char[] open , char[] close , int[] arr){
int l = 0;
for (int i = 0 ; i < arr.length ; i++)
l += arr[i];
l *= 2;
paranthesis_combination_sub(open , close , arr , new int[arr.length] , new int[arr.length], new StringBuilder(), l);
System.out.println(paran_count + " : " + valid_paran_count);
return;
}
static void paranthesis_combination_sub(char[] open , char[] close, int[] arr , int[] open_so_far , int[] close_so_far, StringBuilder strbld , int l){
if (strbld.length() == l && valid_paran(open , close , strbld)){
System.out.println(new String(strbld));
valid_paran_count++;
return;
}
for (int i = 0 ; i < open.length ; i++){
if (open_so_far[i] < arr[i]){
strbld.append(open[i]);
open_so_far[i]++;
paranthesis_combination_sub(open , close, arr , open_so_far , close_so_far, strbld , l);
open_so_far[i]--;
strbld.deleteCharAt(strbld.length() -1 );
}
}
for (int i = 0 ; i < open.length ; i++){
if (close_so_far[i] < open_so_far[i]){
strbld.append(close[i]);
close_so_far[i]++;
paranthesis_combination_sub(open , close, arr , open_so_far , close_so_far, strbld , l);
close_so_far[i]--;
strbld.deleteCharAt(strbld.length() -1 );
}
}
return;
}
Cn is the nth Catalan number, C(2n,n)/(n+1), and gives the number of valid strings of length 2n that use only (). So if we change all [] and {} into (), there would be Cn1+n2+n3 ways. Then there are C(n1+n2+n3,n1) ways to change n1 () back to {}, and C(n2+n3,n3) ways to change the remaining () into []. Putting that all together, there are C(2n1+2n2+2n3,n1+n2+n3)C(n1+n2+n3,n1)C(n2+n3,n3)/(n1+n2+n3+1) ways.
As a check, when n1=2, n2=n3=1, we have C(8,4)C(4,2)C(2,1)/5=168.
In general, infinitely. However I assume, that you meant to find how many combinations are there provided limited string length. For simplicity lets assume that the limit is an even number. Then, lets create an initial string:
(((...()...))) with length equal to the limit.
Then, we can switch any instance of () pair with [] or {} parenthesis. However, if we change an opening brace, then we ought to change the matching closing brace. So, we can look only at the opening braces, or at pairs. For each parenthesis pair we have 4 options:
leave it unchanged
change it to []
change it to {}
remove it
So, for each of (l/2) objects we choose one of four labels, which gives:
4^(l/2) possibilities.
EDIT: this assumes only "concentric" parenthesis strings (contained in each other), as you've suggested in your edit. Intuitively however, a valid combination is also: ()[]{} - this solution does not take this into account.