Calculate and list how many different 4 digit numbers can be done with the numbers 0 to 9? - emeditor

There is something I want to learn.
Let's say we have some single digit numbers.
Example: 1-2-3-4-5-6-7-8-9-0
Example II: 1-2-4-6-0
And with these numbers, we want to get 4-digit numbers that are different from each other.
And we want to print them as lists.
Result:
4676
4236
1247
1236
....
Is it possible to do this?

You can write and run a macro like this:
// retrieve the selected text
str = document.selection.Text;
// check the input string format. The input must be something like: "1-2-4-6-0"
if( str.length == 0 ) {
alert( "Select the input string" );
Quit();
}
for( i = 0; i < str.length; ++i ) {
c = str.substr( i, 1 );
if( i % 2 == 0 ) {
if( c < '0' || c > '9' ) {
alert( "not digit" );
Quit();
}
}
else {
if( c != '-' ) {
alert( "not separated by '-'" );
Quit();
}
}
}
var arr = new Array();
j = 0;
for( i = 0; i < str.length; ++i ) {
if( i % 2 == 0 ) {
c = str.substr( i, 1 );
arr[j++] = c;
}
}
if( arr.length < 4 ) {
alert( "Input string should contain at least 4 digits" );
Quit();
}
// list all 4-digit combinations
len = arr.length;
str = "";
for( i = 0; i < len; ++i ) {
for( j = 0; j < len; ++j ) {
for( k = 0; k < len; ++k ) {
for( l = 0; l < len; ++l ) {
str += arr[i] + arr[j] + arr[k] + arr[l] + "\r\n";
}
}
}
}
// write the list in a new document
editor.EnableTab = true;
editor.NewFile();
document.write( str );
To run this, save this code as, for instance, GenCombinations.jsee, and then select this file from Select... in the Macros menu. Finally, select Run GenCombinations.jsee in the Macros menu after selecting an input string.

Related

Optimised Macro to sort Column Order based on Headers

Any thoughts on how to sort very large multi-column data via a macro. So for example, sorting all the columns (or perhaps just the selected adjacent columns?) by A-Z, or 0-9, etc. Similar to the Current single Column sorting options.
Assuming you want to sort all columns by looking at the first row of each column, I wrote a macro:
function SortOneColumn()
{
count = document.GetColumns();
arr = new Array(count);
for( i = 0; i < count; ++i ) {
s = document.GetCell( 1, i + 1, eeCellIncludeNone );
arr[i] = { name: s, col: i };
}
arr.sort( function( a, b ) {
var nameA = a.name.toLowerCase();
var nameB = b.name.toLowerCase();
if( nameA < nameB ) {
return -1;
}
if( nameA > nameB ) {
return 1;
}
return 0;
});
bSorted = false;
for( i = 0; i < count; ++i ) {
if( arr[i].col != i ) {
document.MoveColumn( arr[i].col + 1, arr[i].col + 1, i + 1 );
bSorted = true;
break;
}
}
return bSorted;
}
while( SortOneColumn() );
There is a potential for optimizing the macro even further, so please let me know if this is not fast enough.
To run this, save this code as, for instance, SortColumns.jsee, and then select this file from Select... in the Macros menu. Finally, select Run SortColumns.jsee in the Macros menu.

Optimised EmEditor Macro to return Min/Max column lengths on large delimited data

I currently have large delimited data sets and I need to return the min\max lengths for each column.
I'm currently using the following code in Emeditor v20.3, which works great, but am wondering if there is a quicker way, particularly when there are million of lines of data and hundreds of columns (and this code is slow).
Any quicker approaches or ideas would that could be wrapped into a javascript macro would be much appreciated.
for( col = colStart; col <= MaxCol; col++ ) {
sTitle = document.GetCell( 1, col, eeCellIncludeNone );
min = -1;
max = 0;
for( line = document.HeadingLines + 1; line < MaxLines; line++ ) {
str = document.GetCell( line, col, eeCellIncludeQuotesAndDelimiter );
if( min == -1 || min > str.length ) {
min = str.length;
}
if( max < str.length ) {
max = str.length;
}
}
OutputBar.writeln( col + min + " " + max + " " + sTitle);
}
Please update EmEditor to 20.3.906 or later, and run this macro:
colStart = 1;
MaxCol = document.GetColumns();
document.selection.EndOfDocument();
yLastLine = document.selection.GetActivePointY( eePosCellLogical );
min = -1;
max = 0;
for( col = colStart; col <= MaxCol; col++ ) {
sTitle = document.GetCell( 1, col, eeCellIncludeNone );
document.selection.SetActivePoint( eePosCellLogical, col, 1 );
editor.ExecuteCommandByID( 4064 ); // Find Empty or Shortest Cell
y = document.selection.GetActivePointY( eePosCellLogical );
if( y < yLastLine ) { // check if not the last empty line
str = document.GetCell( y, col, eeCellIncludeQuotes );
min = str.length;
}
else { // if the last empty line
document.selection.SetActivePoint( eePosCellLogical, col, 1 );
editor.ExecuteCommandByID( 4050 ); // Find Non-empty Shortest Cell
y = document.selection.GetActivePointY( eePosCellLogical );
str = document.GetCell( y, col, eeCellIncludeQuotes );
min = str.length;
}
document.selection.SetActivePoint( eePosCellLogical, col, 1 );
editor.ExecuteCommandByID( 4049 ); // Find Longest Cell
y = document.selection.GetActivePointY( eePosCellLogical );
str = document.GetCell( y, col, eeCellIncludeQuotes );
max = str.length;
OutputBar.writeln( col + " : " + min + " " + max + " " + sTitle);
}

why not pass all test case in problem balanced numbers in codewars?

Currently i am doing a challenge in codewars on Balanced numbers and i wrote the code in dart and it successfully completed 100 test cases but for long numbers it is not working properly...So i think that it need some conditions for this long numbers:
String balancedNum(numb) {
// your code here
var numb1 = numb.toString();
List a = numb1.split("");
var left_sum = 0;
var right_sum = 0;
for (var i = 0; i <= a.length / 2; i++) {
left_sum += int.parse(a[i]);
}
List<String> b = a.reversed.toList();
//print(b);
for (var i = 0; i < b.length / 2; i++) {
right_sum += int.parse(b[i]);
}
//print(right_sum);
if (left_sum == right_sum) {
return 'Balanced';
} else {
return 'Not Balanced';
}
}
link to the challenge:https://www.codewars.com/kata/balanced-number-special-numbers-series-number-1/train/dart
The compiler verdict for the code is wrong answer because of a simple logical error.
This is because the length of the list has not been calculated correctly
Kindly have a look at the corrected code below, which passes all the 110 test on the platform:
String balancedNum(numb) {
// your code here
var numb1 = numb.toString();
List a = numb1.split("");
var left_sum = 0;
var right_sum = 0;
double d = ((a.length-1) / 2);
int len = d.floor();
print(len);
for (var i = 0; i < len; i++) {
left_sum += int.parse(a[i]);
}
List<String> b = a.reversed.toList();
print(b);
for (var i = 0; i < len; i++) {
right_sum += int.parse(b[i]);
}
print(left_sum);
print(right_sum);
if (left_sum == right_sum) {
return 'Balanced';
} else {
return 'Not Balanced';
}
}
Your problem is not about "long numbers" since you code also fails for the test case using the number 13.
You properly did not read the following rules:
If the number has an odd number of digits then there is only one middle digit, e.g. 92645 has middle digit 6; otherwise, there are two middle digits , e.g. 1301 has middle digits 3 and 0
The middle digit(s) should not be considered when determining whether a number is balanced or not, e.g 413023 is a balanced number because the left sum and right sum are both 5.
So you need to test if the number are even or uneven since we need to use that information to know how many digits we should use in the sum on each side.
I have done that in the following implementation:
String balancedNum(int numb) {
final numb1 = numb.toString();
final a = numb1.split("");
var split = (a.length / 2).floor();
if (a.length % 2 == 0) {
split--; // the number is even
}
var left_sum = 0;
var right_sum = 0;
for (var i = 0; i < split; i++) {
print(a[i]);
left_sum += int.parse(a[i]);
}
final b = a.reversed.toList();
for (var i = 0; i < split; i++) {
right_sum += int.parse(b[i]);
}
if (left_sum == right_sum) {
return 'Balanced';
} else {
return 'Not Balanced';
}
}

Finding longest sequence of '1's in a binary array by replacing any one '0' with '1'

I have an array which is constituted of only 0s and 1s. Task is to find index of a 0, replacing which with a 1 results in the longest possible sequence of ones for the given array.
Solution has to work within O(n) time and O(1) space.
Eg:
Array - 011101101001
Answer - 4 ( that produces 011111101001)
My Approach gives me a result better than O(n2) but times out on long string inputs.
int findIndex(int[] a){
int maxlength = 0; int maxIndex= -1;
int n=a.length;
int i=0;
while(true){
if( a[i] == 0 ){
int leftLenght=0;
int j=i-1;
//finding count of 1s to left of this zero
while(j>=0){
if(a[j]!=1){
break;
}
leftLenght++;
j--;
}
int rightLenght=0;
j=i+1;
// finding count of 1s to right of this zero
while(j<n){
if(a[j]!=1){
break;
}
rightLenght++;
j++;
}
if(maxlength < leftLenght+rightLenght + 1){
maxlength = leftLenght+rightLenght + 1;
maxIndex = i;
}
}
if(i == n-1){
break;
}
i++;
}
return maxIndex;
}
The approach is simple, you just need to maintain two numbers while iterating through the array, the current count of the continuous block of one, and the last continuous block of one, which separated by zero.
Note: this solution assumes that there will be at least one zero in the array, otherwise, it will return -1
int cal(int[]data){
int last = 0;
int cur = 0;
int max = 0;
int start = -1;
int index = -1;
for(int i = 0; i < data.length; i++){
if(data[i] == 0){
if(max < 1 + last + cur){
max = 1 + last + cur;
if(start != -1){
index = start;
}else{
index = i;
}
}
last = cur;
start = i;
cur = 0;
}else{
cur++;
}
}
if(cur != 0 && start != -1){
if(max < 1 + last + cur){
return start;
}
}
return index;
}
O(n) time, O(1) space
Live demo: https://ideone.com/1hjS25
I believe the problem can we solved by just maintaining a variable which stores the last trails of 1's that we saw before reaching a '0'.
int last_trail = 0;
int cur_trail = 0;
int last_seen = -1;
int ans = 0, maxVal = 0;
for(int i = 0; i < a.size(); i++) {
if(a[i] == '0') {
if(cur_trail + last_trail + 1 > maxVal) {
maxVal = cur_trail + last_trail + 1;
ans = last_seen;
}
last_trail = cur_trail;
cur_trail = 0;
last_seen = i;
} else {
cur_trail++;
}
}
if(cur_trail + last_trail + 1 > maxVal && last_seen > -1) {
maxVal = cur_trail + last_trail + 1;
ans = last_seen;
}
This can be solved by a technique that is known as two pointers. Most two-pointers use O(1) space and O(n) time.
Code : https://www.ideone.com/N8bznU
#include <iostream>
#include <string>
using namespace std;
int findOptimal(string &s) {
s += '0'; // add a sentinel 0
int best_zero = -1;
int prev_zero = -1;
int zeros_in_interval = 0;
int start = 0;
int best_answer = -1;
for(int i = 0; i < (int)s.length(); ++i) {
if(s[i] == '1') continue;
else if(s[i] == '0' and zeros_in_interval == 0) {
zeros_in_interval++;
prev_zero = i;
}
else if(s[i] == '0' and zeros_in_interval == 1) {
int curr_answer = i - start; // [start, i) only contains one 0
cout << "tried this : [" << s.substr(start, i - start) << "]\n";
if(curr_answer > best_answer) {
best_answer = curr_answer;
best_zero = prev_zero;
}
start = prev_zero + 1;
prev_zero = i;
}
}
cout << "Answer = " << best_zero << endl;
return best_zero;
}
int main() {
string input = "011101101001";
findOptimal(input);
return 0;
}
This is an implementation in C++. The output looks like this:
tried this : [0111]
tried this : [111011]
tried this : [1101]
tried this : [10]
tried this : [01]
Answer = 4

For a given string which contains only digits , what's the optimal approach to return all valid ip address combinations?

Example:
Given “25525511135”
Output : [“255.255.11.135”, “255.255.111.35”]. (sorted order)
Kindly let me know if we could do a depth first search over here ?(that's the only thing striking me )
Why is it important to have an 'optimal' approach for answering this?
There are not many permutations so the simple approach of checking every combination that fits into the IP format and then filtering out those that have out of range numbers will easily work.
It's unlikely to be a bottle neck for whatever this is part of.
You probably want a dynamic programming algorithm for the general case (something like
http://www.geeksforgeeks.org/dynamic-programming-set-32-word-break-problem/).
Instead of testing whether prefixes can be segmented into words in the dictionary, you'd be testing to see whether the prefixes are prefixes of some valid IPv4 address.
Brutal DFS is acceptable in this problem:
class Solution{
private:
vector<string> ans;
int len;
string cur, rec, str;
bool IsOk(string s) {
if(s[0] == '0' && s.size() > 1) return false;
int sum = 0;
for(int i = 0; i < s.size(); i ++) {
if(s[i] == '.') return false;
sum = sum * 10 + s[i] - '0';
}
if(sum >= 0 && sum <= 255) return true;
return false;
}
void dfs(int x, int cnt) {
if(x == len) {
if(str.size() != len + 4) return ;
string tmp(str);
tmp.erase(tmp.size() - 1, 1);
if(cnt == 4) ans.push_back(tmp);
return ;
}
if(cnt > 4 || str.size() > len + 4) return ;
string tmp = cur;
cur += rec[x];
if(!IsOk(cur)) {
cur = tmp;
return ;
}
dfs(x + 1, cnt);
string tmp2 = cur + '.';
str += tmp2;
cur = "";
dfs(x + 1, cnt + 1);
str.erase(str.size() - tmp2.size(), tmp2.size());
cur = tmp;
}
public:
vector<string> restoreIpAddresses(string s) {
this->len = s.size();
this->rec = s;
cur = str = "";
ans.clear();
dfs(0, 0);
return ans;
}
};
Here is a recursive solution on JavaScript. The result is not sorted.
// Task from https://www.geeksforgeeks.org/program-generate-possible-valid-ip-addresses-given-string/
// Given a string containing only digits, restore it by returning all possible valid IP address combinations.
//
// Example:
// Input : 25525511135
// Output : [“255.255.11.135”, “255.255.111.35”]
//
(function () {
function getValidIP(str) {
const result = [];
const length = str.length;
check(0, 0, '');
function check(start, level, previous){
let i = 0;
let num;
if (level === 3) {
num = str.substring(start);
if (num && num < 256) {
result.push(`${previous}.${num}`);
}
return;
}
num = str.substring(start, start + 1);
if (num == 0) {
check(start + 1, level + 1, level === 0 ? `${num}`: `${previous}.${num}`);
} else {
while (num.length < 4 && num < 256 && start + i + 1 < length) {
check(start + i + 1, level + 1, level === 0 ? `${num}`: `${previous}.${num}`);
i++;
num = str.substring(start, start + i + 1);
}
}
}
return result;
}
console.log('12345:')
console.time('1-1');
console.log(getValidIP('12345'));
console.timeEnd('1-1');
console.log('1234:')
console.time('1-2');
console.log(getValidIP('1234'));
console.timeEnd('1-2');
console.log('2555011135:')
console.time('1-3');
console.log(getValidIP('2555011135'));
console.timeEnd('1-3');
console.log('222011135:')
console.time('1-4');
console.log(getValidIP('222011135'));
console.timeEnd('1-4');
})();

Resources