Remove spaces between digits in a string [closed] - algorithm

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
original: "I have the M5 2 0 0 and I like it"
intended: "I have the M5200 and I like it"
How would you achieve this as an algoritm or give a code example?
I believe this question is valid in many programming languages so I won't ask it for a specific one.

C# sample (replacing with regular expression):
String original = "I have the M5 2 0 0 and I like it";
String result = Regex.Replace(original, #"\d( *\d*)*\d",
(MatchEvaluator) (match => {
return match.Value.Replace(" ", "");
}));

For languages that don't have regular expressions: iterate through the text. If the current letter is a space and the letters surrounding it are digits, then don't add it to the result.
Sample Python implementation:
text = "I have the M5 2 0 0 and I like it"
result = []
for i in range(len(text)):
if i > 0 and i < len(text)-1:
prev = text[i-1]
next = text[i+1]
if text[i] == ' ' and prev.isdigit() and next.isdigit():
continue
result.append(text[i])
print "".join(result)
Result:
I have the M5200 and I like it

For python you can use:
import re
line = 'I have the M5 2 0 0 and I like it'
line = re.sub(r'(\d+)\s+(?=\d)',r'\1', line)
print(line)
where \1 stands for the first group \d+ and the second group will not be replaced ?=\d because is only used for matching.
Result: I have the M5200 and I like it

A Java solution:
public static void main(String[] args) {
String input = "I have the M5 231 0 0 and I like it";
String output = "";
if ( input.length() > 0 ) {
output += input.charAt(0);
}
for ( int i = 1 ; i < input.length()-1 ; i++ ) {
if ( Character.isDigit(input.charAt(i-1)) &&
Character.isDigit(input.charAt(i+1)) &&
Character.isSpaceChar(input.charAt(i)) ) {
continue;
} else {
output += input.charAt(i);
}
}
if ( input.length() > 1 ) {
output += input.charAt(input.length() - 1);
}
System.out.println(output);
}

Related

Find the Big-O of some functions [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
Hey I'm having some troubling find the what's Big-O this function have, can anyone help me please?, also can you explain how you solved it?, Thanks to everyone(:
public static Node<Polinom> SumPolinoms(Node<Polinom> polinom1, Node<Polinom> polinom2) // 2.B
{
Node<Polinom> temp1, temp2, result, first;
temp1 = polinom1;
temp2 = polinom2;
first = result = new Node<Polinom>(new Polinom(0, 0));
while (temp1 != null && temp2 != null)
{
if (temp1.GetValue().GetPower() == temp2.GetValue().GetPower())
{
result.SetNext(new Node<Polinom>(new Polinom(temp1.GetValue().GetFactor() + temp2.GetValue().GetFactor(), temp1.GetValue().GetPower())));
temp1 = temp1.GetNext();
temp2 = temp2.GetNext();
}
else if (temp1.GetValue().GetPower() < temp2.GetValue().GetPower())
{
result.SetNext(new Node<Polinom>(temp2.GetValue()));
temp2 = temp2.GetNext();
}
else
{
result.SetNext(new Node<Polinom>(temp1.GetValue()));
temp1 = temp1.GetNext();
}
result = result.GetNext();
}
while (temp1 != null)
{
result.SetNext(new Node<Polinom>(temp1.GetValue()));
temp1 = temp1.GetNext();
result = result.GetNext();
}
while (temp2 != null)
{
result.SetNext(new Node<Polinom>(temp2.GetValue()));
temp2 = temp2.GetNext();
result = result.GetNext();
}
return first.GetNext();
}
I may have misunderstood the code, but wouldn’t this be O(2n), because it just runs through each item of temp1 and temp2. O(2n) simplifies to O(n). The code could also be greatly simplified.

How to ensure minimum occurrences of RNG outcomes?

I'm working on a basic password generator for This Reddit Programming Exercise. I have very simple password generation working in Kotlin, but I'm struggling to come up with a good way to guarantee a specific minimum number of each character type (i.e. at least 2 each of Upper, Lower, Digit, and special character).
I could easily just do two of each to start the password, but I want them to be randomly distributed, not all front-loaded. I also thought of inserting the characters randomly into a character array, rather than appending to a string, but I was wondering if maybe there is a better way.
Here is what I have currently:
private fun generatePassword() {
var password = ""
val passwordLength = (8..25).random()
for (i in 0..passwordLength) {
val charType = (1..5).random()
when (charType) {
1 -> password += lettersLower[(0..lettersLower.size).random()]
2 -> password += lettersUpper[(0..lettersUpper.size).random()]
3 -> password += numbers[(0..numbers.size).random()]
4 -> password += symbols[(0..symbols.size).random()]
}
}
println(password)
}
This works and generates a random password of a random length of 8-24 characters, and contains a random combination of uppercase letters, lowercase letters, digits, and special characters, but it doesn't guarantee the presence of any specific number of each type, like most websites require nowadays.
I thought of doing something like this:
private fun generatePassword() {
var password: ArrayList<Char> = arrayListOf()
var newChar:Char
var numLow = 0
var numUpp = 0
var numDig = 0
var numSpe = 0
while (numLow < 2){
newChar = lettersLower[(0..lettersLower.size).random()]
password.add((0..password.size).random(), newChar)
numLow++
}
while (numUpp < 2){
newChar = lettersUpper[(0..lettersUpper.size).random()]
password.add((0..password.size).random(), newChar)
numUpp++
}
while (numDig < 2){
newChar = numbers[(0..numbers.size).random()]
password.add((0..password.size).random(), newChar)
numDig++
}
while (numSpe < 2){
newChar = symbols[(0..symbols.size).random()]
password.add((0..password.size).random(), newChar)
numSpe++
}
val passwordLength = (8..25).random() - password.size
for (i in 0..passwordLength) {
val charType = (1..5).random()
when (charType) {
1 -> {
newChar = lettersLower[(0..lettersLower.size).random()]
password.add(newChar)
}
2 -> {
newChar = lettersUpper[(0..lettersUpper.size).random()]
password.add(newChar)
}
3 -> {
newChar = numbers[(0..numbers.size).random()]
password.add(newChar)
}
4 -> {
newChar = symbols[(0..symbols.size).random()]
password.add(newChar)
}
}
}
for (i in password.indices){
print(password[i])
}
print("\n")
}
But that doesn't seem particularly concise. The other option I thought of is to check if the password contains two of each type of character and generate a new one if it doesn't, but that seems awfully inefficient. Is there a better way to ensure that if I run my RNG 8+ times it will return at least, but not exactly, two ones, two twos, two threes, and two fours?
Here's my random function, if that helps:
// Random function via SO user #s1m0nw1 (https://stackoverflow.com/a/49507413)
private fun ClosedRange<Int>.random() = (Math.random() * (endInclusive - start) + start).toInt()
I also found this SO post in Java, but it's also not very concise and I'm wondering if there is a more general purpose, more concise solution to ensure a minimum number of occurrences for each possible outcome of an RNG over a number of trials greater than the sum of those minimum occurrences.
Sorry for the rambling post. Thanks in advance for your insight.
I think your second version is on the right track. It can be simplified to:
import java.util.Random
fun generatePassword() : String {
// this defines the classes of characters
// and their corresponding minimum occurrences
val charClasses = arrayOf(
('a'..'z').asIterable().toList() to 2,
('A'..'Z').asIterable().toList() to 2,
('0'..'9').asIterable().toList() to 2,
"!##$%^&*()_+".asIterable().toList() to 2
)
val maxLen = 24;
val minLen = 8;
var password = StringBuilder()
val random = Random()
charClasses.forEach {(chars, minOccur) ->
(0..minOccur).forEach {
password.insert(
if (password.isEmpty()) 0 else random.nextInt(password.length),
chars[random.nextInt(chars.size)])
}
}
((password.length + 1)..(random.nextInt(maxLen - minLen + 1) + minLen)).forEach {
val selected = charClasses[random.nextInt(charClasses.size)]
password.append(selected.first[random.nextInt(selected.first.size)])
}
return password.toString()
}

appending strings together in VS2010 c++

I have written a code that have a if condition. After checking if then I want to show the results in a TexBox. The if statement is satisfied for more than one case and then I need to append them.
For example:
for (i=1;i<10;i++){
if (i > 8){
String^ Num = Convert::ToString(i);
textbox1->Text = Num;
}
}
The answer is 10. But I want to have 8,9,10.
How Could I have such a answer?
String^ Num = "";
for (i=1;i<10;i++){
if (i > 8){
Num = Convert::ToString(i);
if(Num == "")//first iteration so don't add ", "
{
textbox1-> += Num;
}
else
{
textbox1->Text += ", " + Num;
}
}
The default behavior of the string::operator+ is to concatenate so += will just concatenate whatever is already in the string with what the new value is. So assuming the Text field is a string this should work. Apologies for the lack of explanation.

Undefined offset ??? PHP my code attached [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
PHP: “Notice: Undefined variable” and “Notice: Undefined index”
i am getting "ranksection" array at run time and after implementing ksort on "ranksection" i wanna move its data upward on null index as i am printing ranksection before moving its data upward if there were any free array i am successfully getting what i want but it also giving error "Undefined Index" i dont know why my code is,
$sortvar = count($ranksection);
$seqnum = 0;
for ($var = 0; $var <= $sortvar; $var++) {
if ($ranksection[$var] != null) {
$sequence[$seqnum] = $ranksection[$var];
$seqnum++;
}
}
print_r($sortvar);
print_r($ranksection);
print_r($sequence);
the result is,
3
Array ( [1] => Self Introduction [2] => Experience in Econometrics and multivariate S [3] => Experience )
Array ( [0] => Self Introduction [1] => Experience in Econometrics and multivariate S [2] => Experience )
Hopes for your suggestions
See your print_r section of second array it starts with index 1 and your $var assigned to 0.
Now here you are trying to access the 0th index. that is why you're getting this error.
Try to use foreach
foreach($ranksection as $key => $value ) {
if ($ranksection[$key] != null) {
$sequence[$seqnum] = $ranksection[$key];
$seqnum++;
}
}
Do this as the condition for your for loop:
for ($var = 0; $var <= $sortvar - 1; $var++) {
The -1 is important since arrays start from 0 and go the length of the array, minus one.
You ought to be using count()-1 in your for loop:
$sortvar = count($ranksection) -1;
$seqnum = 0;
for ($var = 0; $var <= $sortvar; $var++) {
Or, use less than (without less than equal to) as the operator:
for ($var = 0; $var < $sortvar; $var++) {
You're going past the end of your array because:
$sortvar = count($ranksection); // This is 4
Array indexs start at 0, but count returns the number where 1 is the first item, not 0. Do this to fix it:
$sortvar = count($ranksection) - 1;
Or change <= to <
for ($var = 0; $var < $sortvar; $var++) {
if ($ranksection[$var] != null) {
$sequence[$seqnum] = $ranksection[$var];
$seqnum++;
}
}

String: replacing spaces by a number

I would like to replace every blank spaces in a string by a fixnum (which is the number of blank spaces).
Let me give an example:
s = "hello, how are you ?"
omg(s) # => "hello,3how10are2you1?"
Do you see a way (sexy if possible) to update a string like this?
Thank you Rubists :)
gsub can be fed a block for the "replace with" param, the result of the block is inserted into place where the match was found. The argument to the block is the matched string. So to implement this we capture as much whitespace as we can ( /\s+/ ) and feed that into the block each time a section is found, returning that string's length, which gets put back where the whitespace was originally found.
Code:
s = "hello, how are you ?"
res = s.gsub(/\s+/) { |m| m.length }
puts res
# => hello,3how10are2you1?
it is possible to do this via an array split : Javascript example
var s = "hello, how are you ?";
function omg( str ) {
var strArr = str.split('');
var count = 0;
var finalStr = '';
for( var i = 0; i < strArr.length; i++ ) {
if( strArr[i] == ' ' ) {
count++;
}
else
{
if( count > 0 ) {
finalStr += '' + count;
count = 0;
}
finalStr += strArr[i];
}
}
return finalStr
}
alert( omg( s ) ); //"hello,3how10are2you1?"
Lol, this seems the best it can be for javascript

Resources