So I have this code now, and in input I have in ascending order my name's letters "ahimrsu". I need to show up the right number for "mariush" from all combinations which should to be 2170. For now it only show ahimrsu, ahimrus, ahimsru, ahimsur, ahimurs, ahimusr, ahirmus, ahirmsu.... etc How can I do this?
<!DOCTYPE HTML>
<html>
<head>
<!--Script Function Start Here-->
<script type="text/javascript">
function perms(data) {
if (!(data instanceof Array)) {
throw new TypeError("input data must be an Array");
}
data = data.slice(); // make a copy
var permutations = [],
stack = [];
function doPerm() {
if (data.length == 0) {
permutations.push(stack.slice());
}
for (var i = 0; i < data.length; i++) {
var x = data.splice(i, 1);
stack.push(x);
doPerm();
stack.pop();
data.splice(i, 0, x);
}
}
doPerm();
return permutations;
}
var input = "ahimrsu".split('');
var result = perms(input);
for (var i = 0; i < result.length; i++) {
result[i] = result[i].join('');
}
console.log(result);
</script>
<!--Header start here-->
</head>
<body>
<!--Script Result-->
<script type="text/javascript">
document.write(result);
</script>
</body>
</html>
Your question is of mathematics nature - combinations and permutations. You are actually asking the number of possible permutation for string length 7.
The formula is factorial(numOfchar).
In this case 7! = 7x6x5x4x3x2x1 = 5040.
public static void main(String[] args) {
String str = "ABCDEFH";
System.out.println("Number of permutations for " + str + " is : " + factorial(str.length()));
}
public static int factorial(int n)
{
if (n == 0)
return 1;
int result = factorial(n-1)*n;
return result;
}
Program Output:
Number of permutations for ABCDEFH is : 5040
Since you tagged Java, this is one way you can get the it done with Java.
Related
This question already has answers here:
How to use toLocaleString() and tofixed(2) in JavaScript
(3 answers)
Closed 2 years ago.
I am making a currency converter, and I would like the result to have proper comma formatting as well as ALWAYS rounding to two decimals.
For example, if my number is 1000000.3, I would like the result to be 1,000,000.30.
Is there anything that I am missing? I am very new to coding so any help would be appreciated!
EDIT: not seeing that stack overflow is providing an option to run the code, so you could either copy and paste it into a code editor or open the code here: https://xrpalerts.000webhostapp.com/testing.html
<!DOCTYPE html>
<html>
<body>
<script>
var CalculatorResult = 1000000.3
var CalculatorResultLocale = parseFloat(CalculatorResult).toLocaleString("us-EN");
var CalculatorResultLocaleFixed = parseFloat(CalculatorResultLocale).toFixed(2);
var CalculatorResultFixed = parseFloat(CalculatorResult).toFixed(2);
var CalculatorResultFixedLocale = parseFloat(CalculatorResultFixed).toLocaleString("us-EN");
function ClickAllResults() {
document.write("CalculatorResultLocale: ");
document.write(CalculatorResultLocale);
document.write("<br>");
document.write("CalculatorResultLocaleFixed: ");
document.write(CalculatorResultLocaleFixed);
document.write("<br>");
document.write("<br>");
document.write("CalculatorResultFixed: ");
document.write(CalculatorResultFixed);
document.write("<br>");
document.write("CalculatorResultFixedLocale: ");
document.write(CalculatorResultFixedLocale);
document.write("<br>");
}
</script>
<button onclick="ClickAllResults()" id = "button"><strong>Click to see all results</strong></button>
</body>
</html>
To display toLocaleString by decimal place use
.toLocaleString("us-EN", { minimumFractionDigits: 2, maximumFractionDigits: 2 })
you`r code will be like this
var CalculatorResultFixedLocale = parseFloat(CalculatorResultFixed).toLocaleString("us-EN", { minimumFractionDigits: 2, maximumFractionDigits: 2 });
<!DOCTYPE html>
<html>
<body>
<script>
var CalculatorResult = 1000000.3
var CalculatorResultMoney = currencyFormat(CalculatorResult);
function ClickAllResults() {
document.write("CalculatorResultMoney: ");
document.write(CalculatorResultMoney);
document.write("<br>");
}
function currencyFormat(num) {
let a = '$' + num.toFixed(2).replace(/(\d)(?=(\d{3})+(?!\d))/g, '$1,')
return a;
}
</script>
<button onclick="ClickAllResults()" id = "button"><strong>Click to see all results</strong></button>
</body>
</html>
I do find a function similar to your request
https://blog.abelotech.com/posts/number-currency-formatting-javascript/
function currencyFormat(num) {
let a = '$' + num.toFixed(2).replace(/(\d)(?=(\d{3})+(?!\d))/g, '$1,')
return a;
}
function numberWithCommas(x) {
return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}
const round = (value, decimals) => {
return numberWithCommas(Number(Math.round(value + 'e' + decimals) + 'e-' + decimals).toFixed(2));
};
console.log(round(84347.336, 2)); // 84,347.34
console.log(round(8557.332, 2)); // 8,557.33
console.log(round(187, 2)); // 187.00
The toFixed() method formats a number using fixed-point notation.
//execute below function
CommaFormatted('2345643.123')
//result => 2,345,643.123
function CommaFormatted(amount) {
var delimiter = ","; // replace comma if desired
var a = amount.split('.',2)
var d = a[1];
var i = parseInt(a[0]);
if(isNaN(i)) { return ''; }
var minus = '';
if(i < 0) { minus = '-'; }
i = Math.abs(i);
var n = new String(i);
var a = [];
while(n.length > 3) {
var nn = n.substr(n.length-3);
a.unshift(nn);
n = n.substr(0,n.length-3);
}
if(n.length > 0) { a.unshift(n); }
n = a.join(delimiter);
if(d.length < 1) { amount = n; }
else { amount = n + '.' + d; }
amount = minus + amount;
return amount;
}
Please refer CSS trick article https://css-tricks.com/snippets/javascript/comma-values-in-numbers/#:~:text=Javascript%20has%20a%20method%20called,will%20convert%20it%20to%2012%2C345%2C678.90.
Alice has two strings, initial and goal. She can remove some number of characters from initial, which will give her a subsequence of that string. A string with no deletions is still considered a subsequence of itself. Given these two strings, can you find the minimum number of subsequences of initial that, when appended together, will form goal?
Functions
minimumConcat() has two parameters:
initial: the source string that you will get subsequences from
goal: the target string that needs to be formed
Input Format
For some of our templates, we have handled parsing for you. If we do not provide you a parsing function, you will need to parse the input directly. In this problem, our input format is as follows:
The first line is the initial String that we will be generating subsequences from
The second line is the goal String to form
Here is an example of the raw input:
abc
bcbac
Expected Output
Return the number of minimum possible subsequences of initial that can be appended together to form goal.
If there are no possible solutions, return -1.
Example minimumConcat() Input #1
initial: "xyz"
goal: "xzyxz"
Output: 3
function minimumConcat(initial, goal) {
//Put your code here.
return 0;
}
Loop the initial string array to form the goal string array.
function minimumConcat(initial, goal) {
initial = initial.split('');
goal = goal.split('');
let res,count=0;
while(true){
if(goal.length > 0){
res = checkChar(initial,goal);
if(false === res){
return -1;
}
}else{
return count;
}
goal = res;
count++;
}
}
function checkChar(initial,goal){
let started = false;
let foundIndex = 0;
for(let i=0; i<initial.length; i++){
if(initial[i] == goal[foundIndex]){
started = true;
foundIndex++;
}
}
if(started){
return goal.slice(foundIndex);
}else{
return false;
}
}
console.log(minimumConcat('abc','bcbac'));
Here you go!
function minimumConcat(initial, goal) {
let result = 0;
let pattern = '';
let count1 = Array.apply(null, Array(26)).map(Number.prototype.valueOf, 0);
let count2 = Array.apply(null, Array(26)).map(Number.prototype.valueOf, 0);
initial.split('').forEach(c => {
pattern = pattern + c
});
pattern = "^[" + pattern + "]*$";
if (!RegExp(pattern).test(goal)) return -1;
for (let i = 0; i < initial.length; i++) {
count1[initial.charCodeAt(i) - 97]++;
}
for (let i = 0; i < goal.length; i++) {
count2[goal.charCodeAt(i) - 97]++;
}
for (let i = 0; i < 26; i++) {
result += Math.abs(count1[i] - count2[i]);
}
return result;
}
console.log(minimumConcat("abc", "bcbac"));
Since this looks like homework I won't give the solution right away, instead here is a suggestion on how to solve it:
I think the hardest part is finding all the sub-strings if you are using Python that's simplified by itertools as mentioned here.
Edit, I didn't notice the javascript tag, you can get the substring set, without a library, with a couple of for loops.
After having all combinations from initial you can sort them to have the longest first. And then go one by one removing them from goal. Counting every time you remove. If, after iterating over all sub-strings, goal is not an empty string then no subsequence of initial can construct goal.
This answers your question using Java
public static int minimumConcat(String initial, String goal) {
HashSet<Character> set = new HashSet<>();
for(char c : initial.toCharArray()) set.add(c);
for(char c : goal.toCharArray()) {
if(!set.contains(c)) return -1;
}
int j = 0, result = 0;
for(int i = 0; i < goal.length();) {
char c = goal.charAt(i);
while(j < initial.length() && initial.charAt(j) != c) j++;
if(j == initial.length()) {
j = 0;
result++;
} else {
j++;
i++;
}
}
result++;
return result;
}
Here is what I've done with python
def minimumConcat(initial, goal):
#verify that goal has all character of initial
res = 0
for i in goal:
if i in initial:
pass
else:
res=-1;
if res != -1:
while goal!="":
a = removefirstGreatestSubstring(initial,goal)
goal=a["goal"];
if a["has"] ==True :
res=res+1
#find the greatest concat
print(res)
def removefirstGreatestSubstring(initial,goal):
has_subtring = False
start = 0
for car in initial:
if car == goal[start]:
has_subtring= True
start = start+1
finalgoal=goal[start:]
return {"goal": finalgoal, "has":has_subtring}
initial = "abc"
goal = "bcbac"
b = minimumConcat(initial, goal)
I've made it using a different approach with regular expressions.
Here a clean version of the code:
"use strict";
// Solution:
function minimumConcat(initial, goal) {
let result = -1;
let goal_slice = goal;
let exp = "", sub = "";
let initial_concat = "";
let matches = 0, count = 0;
let initial_arr = initial.split('');
for(let i = 0 ; i<initial_arr.length; i++){
for(let j = initial_arr.length ; j>i+1; j--){
sub = initial.slice(i,j);
exp = new RegExp(sub,"ig");
matches = (goal_slice.match(exp) || []).length;
if(matches>=1) {
count +=matches;
initial_concat+=sub.repeat(matches);
goal_slice = goal_slice.slice((goal_slice.lastIndexOf(sub)+sub.length));
}
}
}
result = (initial_concat==goal)? count : result;
return result;
}
// Test cases:
let test_cases = [
{initial:"abc", goal: "abcbc"}, // expected result 2
{initial:"abc", goal: "acdbc"}, // expected result -1
{initial:"bcx", goal: "bcbcbc"}, // expected result 3
{initial:"xyz", goal: "xyyz"}, // expected result 2
]
// Running the tests:
test_cases.forEach(function(item,index){
console.log(minimumConcat(item.initial, item.goal));
});
Also, I've included a debug flag to turn on/off console.log messages in order to anybody could easily understand what is happening on each iteration cycle.
"use strict";
// Shwitch for debugging:
const debug = true;
// Solution:
function minimumConcat(initial, goal) {
let exp = "";
let sub = "";
let match = 0;
let count = 0;
let result = -1;
let goal_slice = goal;
let initial_concat = "";
let initial_arr = initial.split('');
for(let i = 0 ; i<initial_arr.length; i++){
for(let j = initial_arr.length ; j>i+1; j--){
sub = initial.slice(i,j);
exp = new RegExp(sub,"ig");
match = (goal_slice.match(exp) || []).length;
if(match>=1) {
count +=match;
initial_concat+=sub.repeat(match);
goal_slice = goal_slice.slice((goal_slice.lastIndexOf(sub)+sub.length));
}
if(debug){
console.log("-----------------------------");
console.log(" i:", i, " - j:", j);
console.log(" exp:", exp);
console.log(" goal:", goal);
console.log(" goal_slice:", goal_slice);
console.log(" match:",match);
}
}
}
result = (initial_concat==goal)? count : result;
if(debug){
console.log("---RESULTS:--------------------------");
console.log("count:",count);
console.log("goal vs initial_concat: ", goal, " - ", initial_concat);
console.log("result: ", result);
}
return result;
}
// Test cases:
let test_cases = [
{initial:"abc", goal: "abcbc"}, // expected result 2
{initial:"abc", goal: "acdbc"}, // expected result -1
{initial:"bcx", goal: "bcbcbc"}, // expected result 3
{initial:"xyz", goal: "xyyz"}, // expected result 2
]
// Running the tests:
test_cases.forEach(function(item,index){
if(debug){
console.log("-----------------------------");
console.log("TEST CASE #",index,":");
console.table(item);
}
minimumConcat(item.initial, item.goal);
});
here is in php
public function index()
{
$init="abc";
$goal="abacabacabacacb";
$res=$this->minimum($init,$goal);
}
public function check($inital,$goal){
$inital=str_split( $inital);
$goal=str_split( $goal);
for($i=0;$i<sizeof($goal);$i++){
if(!in_array($goal[$i],$inital)){
return -1;
}
}
return 0;
}
public function minimum($inital,$goal){
$res=$this->check($inital,$goal);
if($res==-1){
return -1;
}
$counter=0;
$c=0;
$inital=str_split( $inital);
$goal=str_split( $goal);
for($i=0;$i<sizeof($goal);$i++){
for($j=0;$j<sizeof($inital);$j++){
if(($i+$c)<sizeof($goal)){
echo " ".$i." > ".$j." > ".$c." /// ";
if($goal[$i+$c]==$inital[$j]){
$c+=1;
}
}
}
$counter+=1;
if(($i+$c)>=sizeof($goal)){
break;
}
$c=$c-1;
}
return $counter;
}
Here is my python solution
def check_char(initial, goal):
N = len(initial)
started = False
found_index = 0
for i in range(N):
if (initial[i] == goal[found_index]):
started = True
found_index += 1
if(started):
return goal[found_index:]
else:
return '-'
def minimumConcat(initial, goal):
res = 0
count = 0
while(True):
if( len(goal) > 0 ):
res = check_char(initial, goal)
if(res == '-'):
print(-1)
break;
else:
print(count)
break;
goal = res
count += 1
initial = input()
goal = input()
minimumConcat(initial, goal)
im currently doing an assignment where we have a certain amount of people play a game and each player have an attempt of scoring. The scores will be randomly generated from 1-3. The only problem i have is to store the randomly generated value into the array and then summing them up. This way, i can produce a leader board that say something like "congrats (player name) your total score is (total score)). Any suggestion on how to do these's would be great or better yet, any other alternatives would be appreciated as well. So far i've been using a incremental counter to generate the total score but it keeps generating the same number over and over again e.g. (2,2,2,2...) (1,1,1,1,....)
<HTML>
<!Foundation Page for building our Javascript programs>
<HEAD>
<TITLE>The Foundation Page </TITLE>
<SCRIPT LANGUAGE = "JavaScript">
function main()
{
randomnumber()
totalscore()
}
function randomnumber()
{
var randomnumber;
randomnumber = Math.random()*3;
return(Math.floor(randomnumber+0.5));
}
function totalscore()
{
var n;
var score = 0;
number = randomnumber();
for (n = 0 ; n < 11 ; ++n)
{
if (number == 0)
{
score = score + 0;
}
else if (number == 2)
{
score =score + 2;
}
else if (number == 3)
{
score =score + 3;
}
}
document.write(score)
}
</SCRIPT>
<HEAD>
<BODY>
<BODY BGCOLOUR = "WHITE">
<H2>The Foundation Page </H2>
<HR>
<SCRIPT LANGUAGE = "Javascript"> main() </SCRIPT>
<INPUT NAME = "dobutton" TYPE = "button" value = "Start game" on Click = "game()">
<INPUT NAME = "dobutton" TYPE = "button" value = "Leaderboard" on Click = "leader()">
</BODY>
</HTML>
This may help, although you should try first before posting for solutions.
Create an empty array:
var myArray = [];
Add values to array (from your randomnumber() generator):
myArray.push(randomnumber());
myArray.push(randomnumber());
myArray.push(randomnumber());
Function to sum the values of some array (this is perhaps the most primitive but faster/efficient way to do it):
var sumElements = function(someArray) {
if (someArray == null) return false;
var sum = 0;
for (var i = 0, len = someArray.length; i < len; i++) {
sum += someArray[i];
}
return sum;
}
Call sumElements to find the sum:
sumElements(myArray);
Here is the simplest way to do what you need
var randomArray = [];
var randomSum = 0;
randomArray.push(randomnumber());
randomArray.push(randomnumber());
randomArray.push(randomnumber());
for(var i=0; i<randomArray.lenth; i++){
randomSum += randomArray[i];
}
That's the error I'm getting from the Google Chrome JavaScript console when I try to run my page. It refers me to the following line
function char_counter(var str)
from the following code
<html>
<head>
<script type="text/javascript">
function text_change_steps()
{
/* STEP 1:
Get text from cells
*/
document.write("Okay, we made it into the function.");
var textStart = document.getElementById("ipt").value;
var textTarget = document.getElementById("tgt").value;
/* STEP 2:
Create 2 maps, one for the letters that need added to textStart,
the other for the letters that need removed from textStart.
EXAMPLE:
If textStart="dude" and textTarget="deck", then following procedure
creates 2 maps, needAdded and needRemoved with key-value pairs
needAdded['c']=1, needAdded['k']=1, needRemoved['u']=1,
and needRemoved['d']=1.
*/
var startChars = char_counter(textStart);
var targetChars = char_counter(textTarget);
var needAdded = map_disjunct(startChars, targetChars);
var needRemoved = map_disjunct(targetChars, startChars);
/* STEP 3:
Display what needs removed and what needs added. Demonstrate process.
*/
if (!is_empty(needRemoved))
{
for (var k in needRemoved)
{
document.write("<p>Need to remove " + needRemoved[k] + " occurence" + (needRemoved[k] > 1 ? "s" : "") + " of <i>" + k + "</i></p>");
}
}
}
function char_counter(var str)
{
/* Given a string str, return a map whose keys are the characters contained
in str and whose values are the corresponding count of each character.
EXAMPLE: Given "aabnsab", return retMap where retMap['a']=3, retMap['b']=2,
retMap['n']=1, retMap['s']=1.
*/
var retMap = {};
for (var k = 0, n = str.length; k < n; ++k)
{
if (str[k] in retMap)
++retMap[str[k]];
else
retMap[str[k]] = 1;
}
return retMap;
}
function map_disjunt(var m1, m2)
{
/* Given maps m1 and m2 with the same key type and with values in the set
{0, 1, 2, ...}, return a map whose keys are every key from m1 that is
in m2 and has a value greater than the corresponding one in m2, or is
in m1 but not m2. The value will be the difference.
EXAMPLE:
If m1 has m1['a']=3 and m1['b']=1 and m2 has m2['a']=1, then retMap['a']=2
and retMap['b']=1.
*/
var retMap = {};
for (var k in m1)
{
var otherCount = (k in m2) ? m2[k] : 0;
if (m1[k] > otherCount)
retMap[k] = m1[k] - otherCount;
}
return retMap;
}
function is_empty(var M)
{
/* Function to determine whether a map is empty
*/
for (var k in M)
if (M.hasOwnProperty(k))
return false;
return true;
}
</script>
<style type="text/css">
</style>
</head>
<body>
<p>Staring word:</p>
<input type="text"t id="ipt"/>
<p>Ending text:</p>
<input type="text" id="tgt"/>
<p><button onclick="text_change_steps()">Show transformation steps</button></p>
</body>
</html>
What's the deal??
Function parameters are local to the function anyway, therefore the var is disallowed there.
I'm trying to list all three letter permutations and this is the code I have -
window.permute = function(){
var alphabet = "abcdefghijklmnopqrstuvwxyz";
var searchTerm ="aaa";
var position = 2;
changeString(searchTerm, position);
}
window.changeString = function(searchTerm, position){
if (position <0){
alert(newString);
return;
}
var alphabet = "abcdefghijklmnopqrstuvwxyz"
for (j=0; j < 26;j++){
var newString = searchTerm.substr(0, position) + alphabet[j] + searchTerm.substr(position+1);
var newPosition = position -1;
changeString(newString,newPosition);
}
return;
}
It's not working and I'm not sure why- can anyone help?
var permutate = (function() {
var results = [];
function doPermute(input, output, used, size, level) {
if (size == level) {
var word = output.join('');
results.push(word);
return;
}
level++;
for (var i = 0; i < input.length; i++) {
if (used[i]) {
continue;
}
used[i] = true;
output.push(input[i]);
doPermute(input, output, used, size, level);
used[i] = false;
output.pop();
}
}
return {
getPermutations: function(input, size) {
var chars = input.split('');
var output = [];
var used = new Array(chars.length);
doPermute(chars, output, used, size, 0);
return results;
}
}
})();
for more information, visit http://jinwolf.tumblr.com/post/26476479113/draw-something-cheat
for an working example, check this jsfiddle http://jsfiddle.net/jinwolf/Ek4N5/31/
alert(newString);
newString is not defined right there. Instead, you should use the argument passed:
alert(searchTerm);
Edit: I'm not entirely sure of your approach. It seems overly complicated. This seems to work. I understand that you rather have your own code working, but perhaps this helps you in solving. I don't quite get your substr part.
http://jsfiddle.net/NUG2A/2/
var alphabet = "abc"; // shortened to save time
function permute(text) {
if(text.length === 3) { // if length is 3, combination is valid; alert
console.log(text); // or alert
} else {
var newalphabet = alphabet.split("").filter(function(v) {
return text.indexOf(v) === -1;
}); // construct a new alphabet of characters that are not used yet
// because each letter may only occur once in each combination
for(var i = 0; i < newalphabet.length; i++) {
permute(text + newalphabet[i]); // call permute with current text + new
// letter from filtered alphabet
}
}
}
permute("");
This will result in the following being called:
permute("");
permute("a");
permute("ab");
permute("abc"); // alert
permute("ac");
permute("acb"); // alert
permute("b");
// ...
I'm not sure from your question that you mean "permutations" because usually permutations do not include repeated elements where it looks like you want to include "aaa".
Here are several algorithms for listing permutations you can go check out. If it turns out you mean to have repetitions, it looks like pimvdb has you covered.
Edit: So you know what you are getting into run-time wise:
With repetition (aaa,aab,...): n^k = 26^3 = 17,576
Without repetition (abc,bac,...): n!/(n-k)! = 26!/(26-3)! = 15,600
for (j=0; j < 26;j++){
should be
for (var j=0; j<26; j++) {
Without the declaration, j is a global variable, so it only takes one iteration to get to 26 and then all the loops terminate.
For permutations a recursive algorith as pimvd showed is always nice but don't forget you can just brute force it with for-loops when N is small:
for(int x1=0; x1 < 26; x1++)
for(int x2=0; x2 < 26; x2++)
for(int x3=0; x3 < 26; x3++){
//do something with x1, x2, x3
}
In C#:
void DoPermuation(string s)
{
var pool = new HashSet<string>();
//Permute("", , pool);
pool = Permute(new List<char>(s));
int i = 0;
foreach (var item in pool) Console.WriteLine("{0:D2}: {1}", ++i, item);
}
HashSet<string> Permute(List<char> range)
{
if (range.Count == 1) return new HashSet<string>(new string[] { range[0].ToString() });
var pool = new HashSet<string>();
foreach (var c in range)
{
var list = new List<char>(range);
list.Remove(c);
foreach (var item in Permute(list)) pool.Add(c + item);
}
return pool;
}