$.ajax - POSTing to https - ajax
I am having a small issue sending https though ajax would anyone be able to look at the code below and let me know weather I am doing something wrong.
$(function(){
$('form').submit(function() {
Username = $("input[name=Username]").val();
AccountCode = $("input[name=AccountCode]").val();
MerchantNumber = $("input[name=MerchantNumber]").val();
CustomerNumber = $("input[name=CustomerNumber]").val();
vPassword = $("input[name=Password]").val();
md5 = $.md5(AccountCode+Username+MerchantNumber+CustomerNumber+vPassword);
//MD5[AccountCode+Username+MerchantNumber+CustomerNumber+vPassword]
//alert(md5);
checkout($(this).serialize()+"&password="+md5);
return false;
});
});
function checkout(formstring){
$.ajax({
type: 'POST',
url: "https://services.incard.com.au/processpayment.ashx",
data: formstring,
dataType: 'json',
contentType: "application/x-www-form-urlencoded;charset=utf-8",
beforeSend: function() {
switch (e) {
case 3:
//alert("jajka");
break;
}
},
success: function(data){alert(data);},
error:function(data){alert(data);}
});
return false;
}
/*
* jQuery MD5 Plugin 1.2.1
* https://github.com/blueimp/jQuery-MD5
*
* Copyright 2010, Sebastian Tschan
* https://blueimp.net
*
* Licensed under the MIT license:
* http://creativecommons.org/licenses/MIT/
*
* Based on
* A JavaScript implementation of the RSA Data Security, Inc. MD5 Message
* Digest Algorithm, as defined in RFC 1321.
* Version 2.2 Copyright (C) Paul Johnston 1999 - 2009
* Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet
* Distributed under the BSD License
* See http://pajhome.org.uk/crypt/md5 for more info.
*/
/*jslint bitwise: true */
/*global unescape, jQuery */
(function ($) {
'use strict';
/*
* Add integers, wrapping at 2^32. This uses 16-bit operations internally
* to work around bugs in some JS interpreters.
*/
function safe_add(x, y) {
var lsw = (x & 0xFFFF) + (y & 0xFFFF),
msw = (x >> 16) + (y >> 16) + (lsw >> 16);
return (msw << 16) | (lsw & 0xFFFF);
}
/*
* Bitwise rotate a 32-bit number to the left.
*/
function bit_rol(num, cnt) {
return (num << cnt) | (num >>> (32 - cnt));
}
/*
* These functions implement the four basic operations the algorithm uses.
*/
function md5_cmn(q, a, b, x, s, t) {
return safe_add(bit_rol(safe_add(safe_add(a, q), safe_add(x, t)), s), b);
}
function md5_ff(a, b, c, d, x, s, t) {
return md5_cmn((b & c) | ((~b) & d), a, b, x, s, t);
}
function md5_gg(a, b, c, d, x, s, t) {
return md5_cmn((b & d) | (c & (~d)), a, b, x, s, t);
}
function md5_hh(a, b, c, d, x, s, t) {
return md5_cmn(b ^ c ^ d, a, b, x, s, t);
}
function md5_ii(a, b, c, d, x, s, t) {
return md5_cmn(c ^ (b | (~d)), a, b, x, s, t);
}
/*
* Calculate the MD5 of an array of little-endian words, and a bit length.
*/
function binl_md5(x, len) {
/* append padding */
x[len >> 5] |= 0x80 << ((len) % 32);
x[(((len + 64) >>> 9) << 4) + 14] = len;
var i, olda, oldb, oldc, oldd,
a = 1732584193,
b = -271733879,
c = -1732584194,
d = 271733878;
for (i = 0; i < x.length; i += 16) {
olda = a;
oldb = b;
oldc = c;
oldd = d;
a = md5_ff(a, b, c, d, x[i], 7, -680876936);
d = md5_ff(d, a, b, c, x[i + 1], 12, -389564586);
c = md5_ff(c, d, a, b, x[i + 2], 17, 606105819);
b = md5_ff(b, c, d, a, x[i + 3], 22, -1044525330);
a = md5_ff(a, b, c, d, x[i + 4], 7, -176418897);
d = md5_ff(d, a, b, c, x[i + 5], 12, 1200080426);
c = md5_ff(c, d, a, b, x[i + 6], 17, -1473231341);
b = md5_ff(b, c, d, a, x[i + 7], 22, -45705983);
a = md5_ff(a, b, c, d, x[i + 8], 7, 1770035416);
d = md5_ff(d, a, b, c, x[i + 9], 12, -1958414417);
c = md5_ff(c, d, a, b, x[i + 10], 17, -42063);
b = md5_ff(b, c, d, a, x[i + 11], 22, -1990404162);
a = md5_ff(a, b, c, d, x[i + 12], 7, 1804603682);
d = md5_ff(d, a, b, c, x[i + 13], 12, -40341101);
c = md5_ff(c, d, a, b, x[i + 14], 17, -1502002290);
b = md5_ff(b, c, d, a, x[i + 15], 22, 1236535329);
a = md5_gg(a, b, c, d, x[i + 1], 5, -165796510);
d = md5_gg(d, a, b, c, x[i + 6], 9, -1069501632);
c = md5_gg(c, d, a, b, x[i + 11], 14, 643717713);
b = md5_gg(b, c, d, a, x[i], 20, -373897302);
a = md5_gg(a, b, c, d, x[i + 5], 5, -701558691);
d = md5_gg(d, a, b, c, x[i + 10], 9, 38016083);
c = md5_gg(c, d, a, b, x[i + 15], 14, -660478335);
b = md5_gg(b, c, d, a, x[i + 4], 20, -405537848);
a = md5_gg(a, b, c, d, x[i + 9], 5, 568446438);
d = md5_gg(d, a, b, c, x[i + 14], 9, -1019803690);
c = md5_gg(c, d, a, b, x[i + 3], 14, -187363961);
b = md5_gg(b, c, d, a, x[i + 8], 20, 1163531501);
a = md5_gg(a, b, c, d, x[i + 13], 5, -1444681467);
d = md5_gg(d, a, b, c, x[i + 2], 9, -51403784);
c = md5_gg(c, d, a, b, x[i + 7], 14, 1735328473);
b = md5_gg(b, c, d, a, x[i + 12], 20, -1926607734);
a = md5_hh(a, b, c, d, x[i + 5], 4, -378558);
d = md5_hh(d, a, b, c, x[i + 8], 11, -2022574463);
c = md5_hh(c, d, a, b, x[i + 11], 16, 1839030562);
b = md5_hh(b, c, d, a, x[i + 14], 23, -35309556);
a = md5_hh(a, b, c, d, x[i + 1], 4, -1530992060);
d = md5_hh(d, a, b, c, x[i + 4], 11, 1272893353);
c = md5_hh(c, d, a, b, x[i + 7], 16, -155497632);
b = md5_hh(b, c, d, a, x[i + 10], 23, -1094730640);
a = md5_hh(a, b, c, d, x[i + 13], 4, 681279174);
d = md5_hh(d, a, b, c, x[i], 11, -358537222);
c = md5_hh(c, d, a, b, x[i + 3], 16, -722521979);
b = md5_hh(b, c, d, a, x[i + 6], 23, 76029189);
a = md5_hh(a, b, c, d, x[i + 9], 4, -640364487);
d = md5_hh(d, a, b, c, x[i + 12], 11, -421815835);
c = md5_hh(c, d, a, b, x[i + 15], 16, 530742520);
b = md5_hh(b, c, d, a, x[i + 2], 23, -995338651);
a = md5_ii(a, b, c, d, x[i], 6, -198630844);
d = md5_ii(d, a, b, c, x[i + 7], 10, 1126891415);
c = md5_ii(c, d, a, b, x[i + 14], 15, -1416354905);
b = md5_ii(b, c, d, a, x[i + 5], 21, -57434055);
a = md5_ii(a, b, c, d, x[i + 12], 6, 1700485571);
d = md5_ii(d, a, b, c, x[i + 3], 10, -1894986606);
c = md5_ii(c, d, a, b, x[i + 10], 15, -1051523);
b = md5_ii(b, c, d, a, x[i + 1], 21, -2054922799);
a = md5_ii(a, b, c, d, x[i + 8], 6, 1873313359);
d = md5_ii(d, a, b, c, x[i + 15], 10, -30611744);
c = md5_ii(c, d, a, b, x[i + 6], 15, -1560198380);
b = md5_ii(b, c, d, a, x[i + 13], 21, 1309151649);
a = md5_ii(a, b, c, d, x[i + 4], 6, -145523070);
d = md5_ii(d, a, b, c, x[i + 11], 10, -1120210379);
c = md5_ii(c, d, a, b, x[i + 2], 15, 718787259);
b = md5_ii(b, c, d, a, x[i + 9], 21, -343485551);
a = safe_add(a, olda);
b = safe_add(b, oldb);
c = safe_add(c, oldc);
d = safe_add(d, oldd);
}
return [a, b, c, d];
}
/*
* Convert an array of little-endian words to a string
*/
function binl2rstr(input) {
var i,
output = '';
for (i = 0; i < input.length * 32; i += 8) {
output += String.fromCharCode((input[i >> 5] >>> (i % 32)) & 0xFF);
}
return output;
}
/*
* Convert a raw string to an array of little-endian words
* Characters >255 have their high-byte silently ignored.
*/
function rstr2binl(input) {
var i,
output = [];
output[(input.length >> 2) - 1] = undefined;
for (i = 0; i < output.length; i += 1) {
output[i] = 0;
}
for (i = 0; i < input.length * 8; i += 8) {
output[i >> 5] |= (input.charCodeAt(i / 8) & 0xFF) << (i % 32);
}
return output;
}
/*
* Calculate the MD5 of a raw string
*/
function rstr_md5(s) {
return binl2rstr(binl_md5(rstr2binl(s), s.length * 8));
}
/*
* Calculate the HMAC-MD5, of a key and some data (raw strings)
*/
function rstr_hmac_md5(key, data) {
var i,
bkey = rstr2binl(key),
ipad = [],
opad = [],
hash;
ipad[15] = opad[15] = undefined;
if (bkey.length > 16) {
bkey = binl_md5(bkey, key.length * 8);
}
for (i = 0; i < 16; i += 1) {
ipad[i] = bkey[i] ^ 0x36363636;
opad[i] = bkey[i] ^ 0x5C5C5C5C;
}
hash = binl_md5(ipad.concat(rstr2binl(data)), 512 + data.length * 8);
return binl2rstr(binl_md5(opad.concat(hash), 512 + 128));
}
/*
* Convert a raw string to a hex string
*/
function rstr2hex(input) {
var hex_tab = '0123456789abcdef',
output = '',
x,
i;
for (i = 0; i < input.length; i += 1) {
x = input.charCodeAt(i);
output += hex_tab.charAt((x >>> 4) & 0x0F) +
hex_tab.charAt(x & 0x0F);
}
return output;
}
/*
* Encode a string as utf-8
*/
function str2rstr_utf8(input) {
return unescape(encodeURIComponent(input));
}
/*
* Take string arguments and return either raw or hex encoded strings
*/
function raw_md5(s) {
return rstr_md5(str2rstr_utf8(s));
}
function hex_md5(s) {
return rstr2hex(raw_md5(s));
}
function raw_hmac_md5(k, d) {
return rstr_hmac_md5(str2rstr_utf8(k), str2rstr_utf8(d));
}
function hex_hmac_md5(k, d) {
return rstr2hex(raw_hmac_md5(k, d));
}
$.md5 = function (string, key, raw) {
if (!key) {
if (!raw) {
return hex_md5(string);
} else {
return raw_md5(string);
}
}
if (!raw) {
return hex_hmac_md5(key, string);
} else {
return raw_hmac_md5(key, string);
}
};
}(typeof jQuery === 'function' ? jQuery : this));
In your checkout function, e is not defined. As soon as this ReferenceError occurs, it prevents the form callback from returning false, which allows the form to submit normally and redirects the page.
The entire code block:
beforeSend: function() {
switch (e) {
case 3:
//alert("jajka");
break;
}
},
doesn't do anything at all - just delete that, and the AJAX call will be executed when the form is submitted.
However, you'll now probably run into a separate issue - your comments suggest that the page with this snippet of code is not on the same subdomain (or protocol) as the AJAX request you're trying to complete. Due to the same origin policy, browsers won't allow AJAX requests to different domains, protocols or ports. You'll have to find a way to host the resource on the same domain and protocol to use this code.
(Alternatively, you could use JSONP, although it looks like you're processing a payment here - not the best idea to use a GET request!)
Related
Using a case statement to assign multiple variable in ruby
I'm implementing an HSV to RGB function in ruby, and I was hoping for syntax like this: def hsv_to_rgb(h, s, v) if (h == 0) then return 0, 0, 0 end c = v * s hp = h / 60.0 x = c * (1 - (hp % 2 - 1).abs) r, g, b = case hp when 0..1 c, x, 0 when 1..2 x, c, 0 when 2..3 0, c, x when 3..4 0, x, c when 4..5 x, 0, c else c, 0, x end m = v - c return r + m, g + m, b + m end however, when I attempt to run this in Jruby I get the following error message: SyntaxError: julia2.rb:60: syntax error, unexpected '\n' when 1..2 Does something like this syntax exist in ruby? Thanks!
Your return values in the case statement are not accepted by the ruby engine. I think you want to return an array... using the [] perhaps? Like this: def hsv_to_rgb(h, s, v) if (h == 0) then return 0, 0, 0 end c = v * s hp = h / 60.0 x = c * (1 - (hp % 2 - 1).abs) r, g, b = case hp when 0..1 [c, x, 0] when 1..2 [x, c, 0] when 2..3 [0, c, x] when 3..4 [0, x, c] when 4..5 [x, 0, c] else [c, 0, x] end m = v - c return r + m, g + m, b + m end
Returning array will work and it is more readable as well.
How to fix an Adam's method?
I've such errors: Coordinate .. is not a floating-point number and can't correctly fix it. The program works correctly for a function 1 - t *y , but not for y*y*Exp[t] - 2*y. I will be really happy if you tell me why and how to fix this problem. ABM[a0_, b0_, \[Alpha]_, m0_] := Module[{a = a0, b = b0, F, j, k, m = m0, p}, h = (b - a)/m; T = Table[a, {m + 1}]; Y = Table[\[Alpha], {m + 1}]; For[j = 1, j <= 3, j++, Subscript[k, 1] = h*f[T[[j]], Y[[j]]]; Subscript[k, 2] = h*f[T[[j]] + h/2, Y[[j]] + Subscript[k, 1]/2]; Subscript[k, 3] = h*f[T[[j]] + h/2, Y[[j]] + Subscript[k, 2]/2]; Subscript[k, 4] = h*f[T[[j]] + h, Y[[j]] + Subscript[k, 3]]; Y[[j + 1]] = Y[[j]] + (1/6)*(Subscript[k, 1] + 2*Subscript[k, 2] + 2*Subscript[k, 3] + Subscript[k, 4]); T[[j + 1]] = a + h*j; ]; Subscript[F, 0] = f[T[[1]], Y[[1]]]; Subscript[F, 1] = f[T[[2]], Y[[2]]]; Subscript[F, 2] = f[T[[3]], Y[[3]]]; Subscript[F, 3] = f[T[[4]], Y[[4]]]; For[j = 4, j <= m, j++, p = Y[[j]] + (h/24)*(-9*Subscript[F, 0] + 37*Subscript[F, 1] - 59*Subscript[F, 2] + 55*Subscript[F, 3]); T[[j + 1]] = a + h*j; p = Y[[j]] + (h/24)*(Subscript[F, 1] - 5*Subscript[F, 2] + 19*Subscript[F, 3] + 9*f[T[[j + 1]], p]); Y[[j + 1]] = p; Subscript[F, 0] = Subscript[F, 1]; Subscript[F, 1] = Subscript[F, 2]; Subscript[F, 2] = Subscript[F, 3]; Subscript[F, 3] = f[T[[j + 1]], Y[[j + 1]]]; ]; Return[Transpose[{T, Y}]]]; f[t_, y_] = y*y*Exp[t] - 2*y; Print["Find numerical solutions to the D.E."]; Print["y' = ", f[t, y]]; n = 25; pts1 = ABM[0, 8, 2., n]; Y1 = Y; Needs["Graphics`Colors`"]; graph1 = ListPlot[pts1, PlotJoined -> True, PlotStyle -> Green, PlotRange -> {{0, 10}, {0, 10}}]; Print["The Adams-Bashforth-Moulton solution for y' = ", f[t, y]]; Print["Using n = ", n + 1, " points."]; Print[pts1]; Print[""]; Print["The final value is y(5) = ", Subscript[y, n + 1], " = ", Y[[n + 1]]];
All Possible Tic Tac Toe Winning Combinations
I had an interview were I was asked a seemingly simple algorithm question: "Write an algorithm to return me all possible winning combinations for tic tac toe." I still can't figure out an efficient way to handle this. Is there a standard algorithm or common that should be applied to similar questions like this that I'm not aware of?
This is one of those problems that's actually simple enough for brute force and, while you could use combinatorics, graph theory, or many other complex tools to solve it, I'd actually be impressed by applicants that recognise the fact there's an easier way (at least for this problem). There are only 39, or 19,683 possible combinations of placing x, o or <blank> in the grid, and not all of those are valid. First, a valid game position is one where the difference between x and o counts is no more than one, since they have to alternate moves. In addition, it's impossible to have a state where both sides have three in a row, so they can be discounted as well. If both have three in a row, then one of them would have won in the previous move. There's actually another limitation in that it's impossible for one side to have won in two different ways without a common cell (again, they would have won in a previous move), meaning that: XXX OOO XXX cannot be achieved, while: XXX OOX OOX can be. But we can actually ignore that since there's no way to win two ways without a common cell without having already violated the "maximum difference of one" rule, since you need six cells for that, with the opponent only having three. So I would simply use brute force and, for each position where the difference is zero or one between the counts, check the eight winning possibilities for both sides. Assuming only one of them has a win, that's a legal, winning game. Below is a proof of concept in Python, but first the output of time when run on the process sending output to /dev/null to show how fast it is: real 0m0.169s user 0m0.109s sys 0m0.030s The code: def won(c, n): if c[0] == n and c[1] == n and c[2] == n: return 1 if c[3] == n and c[4] == n and c[5] == n: return 1 if c[6] == n and c[7] == n and c[8] == n: return 1 if c[0] == n and c[3] == n and c[6] == n: return 1 if c[1] == n and c[4] == n and c[7] == n: return 1 if c[2] == n and c[5] == n and c[8] == n: return 1 if c[0] == n and c[4] == n and c[8] == n: return 1 if c[2] == n and c[4] == n and c[6] == n: return 1 return 0 pc = [' ', 'x', 'o'] c = [0] * 9 for c[0] in range (3): for c[1] in range (3): for c[2] in range (3): for c[3] in range (3): for c[4] in range (3): for c[5] in range (3): for c[6] in range (3): for c[7] in range (3): for c[8] in range (3): countx = sum([1 for x in c if x == 1]) county = sum([1 for x in c if x == 2]) if abs(countx-county) < 2: if won(c,1) + won(c,2) == 1: print " %s | %s | %s" % (pc[c[0]],pc[c[1]],pc[c[2]]) print "---+---+---" print " %s | %s | %s" % (pc[c[3]],pc[c[4]],pc[c[5]]) print "---+---+---" print " %s | %s | %s" % (pc[c[6]],pc[c[7]],pc[c[8]]) print As one commenter has pointed out, there is one more restriction. The winner for a given board cannot have less cells than the loser since that means the loser just moved, despite the fact the winner had already won on the last move. I won't change the code to take that into account but it would be a simple matter of checking who has the most cells (the last person that moved) and ensuring the winning line belonged to them.
Another way could be to start with each of the eight winning positions, xxx --- --- xxx --- --- ... etc., and recursively fill in all legal combinations (start with inserting 2 o's, then add an x for each o ; avoid o winning positions): xxx xxx xxx oo- oox oox --- o-- oox ... etc.,
Today I had an interview with Apple and I had the same question. I couldn't think well at that moment. Later one on, before going to a meeting I wrote the function for the combinations in 15 minutes, and when I came back from the meeting I wrote the validation function again in 15 minutes. I get nervous at interviews, Apple not trusts my resume, they only trust what they see in the interview, I don't blame them, many companies are the same, I just say that something in this hiring process doesn't look quite smart. Anyways, here is my solution in Swift 4, there are 8 lines of code for the combinations function and 17 lines of code to check a valid board. Cheers!!! // Not used yet: 0 // Used with x : 1 // Used with 0 : 2 // 8 lines code to get the next combination func increment ( _ list: inout [Int], _ base: Int ) -> Bool { for digit in 0..<list.count { list[digit] += 1 if list[digit] < base { return true } list[digit] = 0 } return false } let incrementTicTacToe = { increment(&$0, 3) } let win0_ = [0,1,2] // [1,1,1,0,0,0,0,0,0] let win1_ = [3,4,5] // [0,0,0,1,1,1,0,0,0] let win2_ = [6,7,8] // [0,0,0,0,0,0,1,1,1] let win_0 = [0,3,6] // [1,0,0,1,0,0,1,0,0] let win_1 = [1,4,7] // [0,1,0,0,1,0,0,1,0] let win_2 = [2,5,8] // [0,0,1,0,0,1,0,0,1] let win00 = [0,4,8] // [1,0,0,0,1,0,0,0,1] let win11 = [2,4,6] // [0,0,1,0,1,0,1,0,0] let winList = [ win0_, win1_, win2_, win_0, win_1, win_2, win00, win11] // 16 lines to check a valid board, wihtout countin lines of comment. func winCombination (_ tictactoe: [Int]) -> Bool { var count = 0 for win in winList { if tictactoe[win[0]] == tictactoe[win[1]], tictactoe[win[1]] == tictactoe[win[2]], tictactoe[win[2]] != 0 { // If the combination exist increment count by 1. count += 1 } if count == 2 { return false } } var indexes = Array(repeating:0, count:3) for num in tictactoe { indexes[num] += 1 } // '0' and 'X' must be used the same times or with a diference of one. // Must one and only one valid combination return abs(indexes[1] - indexes[2]) <= 1 && count == 1 } // Test var listToIncrement = Array(repeating:0, count:9) var combinationsCount = 1 var winCount = 0 while incrementTicTacToe(&listToIncrement) { if winCombination(listToIncrement) == true { winCount += 1 } combinationsCount += 1 } print("There is \(combinationsCount) combinations including possible and impossible ones.") print("There is \(winCount) combinations for wining positions.") /* There are 19683 combinations including possible and impossible ones. There are 2032 combinations for winning positions. */ listToIncrement = Array(repeating:0, count:9) var listOfIncremented = "" for _ in 0..<1000 { // Win combinations for the first 1000 combinations _ = incrementTicTacToe(&listToIncrement) if winCombination(listToIncrement) == true { listOfIncremented += ", \(listToIncrement)" } } print("List of combinations: \(listOfIncremented)") /* List of combinations: , [2, 2, 2, 1, 1, 0, 0, 0, 0], [1, 1, 1, 2, 2, 0, 0, 0, 0], [2, 2, 2, 1, 0, 1, 0, 0, 0], [2, 2, 2, 0, 1, 1, 0, 0, 0], [2, 2, 0, 1, 1, 1, 0, 0, 0], [2, 0, 2, 1, 1, 1, 0, 0, 0], [0, 2, 2, 1, 1, 1, 0, 0, 0], [1, 1, 1, 2, 0, 2, 0, 0, 0], [1, 1, 1, 0, 2, 2, 0, 0, 0], [1, 1, 0, 2, 2, 2, 0, 0, 0], [1, 0, 1, 2, 2, 2, 0, 0, 0], [0, 1, 1, 2, 2, 2, 0, 0, 0], [1, 2, 2, 1, 0, 0, 1, 0, 0], [2, 2, 2, 1, 0, 0, 1, 0, 0], [2, 2, 1, 0, 1, 0, 1, 0, 0], [2, 2, 2, 0, 1, 0, 1, 0, 0], [2, 2, 2, 1, 1, 0, 1, 0, 0], [2, 0, 1, 2, 1, 0, 1, 0, 0], [0, 2, 1, 2, 1, 0, 1, 0, 0], [2, 2, 1, 2, 1, 0, 1, 0, 0], [1, 2, 0, 1, 2, 0, 1, 0, 0], [1, 0, 2, 1, 2, 0, 1, 0, 0], [1, 2, 2, 1, 2, 0, 1, 0, 0], [2, 2, 2, 0, 0, 1, 1, 0, 0] */
This is a java equivalent code sample package testit; public class TicTacToe { public static void main(String[] args) { // TODO Auto-generated method stub // 0 1 2 // 3 4 5 // 6 7 8 char[] pc = {' ' ,'o', 'x' }; char[] c = new char[9]; // initialize c for (int i = 0; i < 9; i++) c[i] = pc[0]; for (int i = 0; i < 3; i++) { c[0] = pc[i]; for (int j = 0; j < 3; j++) { c[1] = pc[j]; for (int k = 0; k < 3; k++) { c[2] = pc[k]; for (int l = 0; l < 3; l++) { c[3] = pc[l]; for (int m = 0; m < 3; m++) { c[4] = pc[m]; for (int n = 0; n < 3; n++) { c[5] = pc[n]; for (int o = 0; o < 3; o++) { c[6] = pc[o]; for (int p = 0; p < 3; p++) { c[7] = pc[p]; for (int q = 0; q < 3; q++) { c[8] = pc[q]; int countx = 0; int county = 0; for(int r = 0 ; r<9 ; r++){ if(c[r] == 'x'){ countx = countx + 1; } else if(c[r] == 'o'){ county = county + 1; } } if(Math.abs(countx - county) < 2){ if(won(c, pc[2])+won(c, pc[1]) == 1 ){ System.out.println(c[0] + " " + c[1] + " " + c[2]); System.out.println(c[3] + " " + c[4] + " " + c[5]); System.out.println(c[6] + " " + c[7] + " " + c[8]); System.out.println("*******************************************"); } } } } } } } } } } } } public static int won(char[] c, char n) { if ((c[0] == n) && (c[1] == n) && (c[2] == n)) return 1; else if ((c[3] == n) && (c[4] == n) && (c[5] == n)) return 1; else if ((c[6] == n) && (c[7] == n) && (c[8] == n)) return 1; else if ((c[0] == n) && (c[3] == n) && (c[6] == n)) return 1; else if ((c[1] == n) && (c[4] == n) && (c[7] == n)) return 1; else if ((c[2] == n) && (c[5] == n) && (c[8] == n)) return 1; else if ((c[0] == n) && (c[4] == n) && (c[8] == n)) return 1; else if ((c[2] == n) && (c[4] == n) && (c[6] == n)) return 1; else return 0; } } `
Below Solution generates all possible combinations using recursion It has eliminated impossible combinations and returned 888 Combinations Below is a working code Possible winning combinations of the TIC TAC TOE game const players = ['X', 'O']; let gameBoard = Array.from({ length: 9 }); const winningCombination = [ [ 0, 1, 2 ], [ 3, 4, 5 ], [ 6, 7, 8 ], [ 0, 3, 6 ], [ 1, 4, 7 ], [ 2, 5, 8 ], [ 0, 4, 8 ], [ 2, 4, 6 ], ]; const isWinningCombination = (board)=> { if((Math.abs(board.filter(a => a === players[0]).length - board.filter(a => a === players[1]).length)) > 1) { return false } let winningComb = 0; players.forEach( player => { winningCombination.forEach( combinations => { if (combinations.every(combination => board[combination] === player )) { winningComb++; } }); }); return winningComb === 1; } const getCombinations = (board) => { let currentBoard = [...board]; const firstEmptySquare = board.indexOf(undefined) if (firstEmptySquare === -1) { return isWinningCombination(board) ? [board] : []; } else { return [...players, ''].reduce((prev, next) => { currentBoard[firstEmptySquare] = next; if(next !== '' && board.filter(a => a === next).length > (gameBoard.length / players.length)) { return [...prev] } return [board, ...prev, ...getCombinations(currentBoard)] }, []) } } const startApp = () => { let combination = getCombinations(gameBoard).filter(board => board.every(item => !(item === undefined)) && isWinningCombination(board) ) printCombination(combination) } const printCombination = (combination)=> { const ulElement = document.querySelector('.combinations'); combination.forEach(comb => { let node = document.createElement("li"); let nodePre = document.createElement("pre"); let textnode = document.createTextNode(JSON.stringify(comb)); nodePre.appendChild(textnode); node.appendChild(nodePre); ulElement.appendChild(node); }) } startApp();
This discovers all possible combinations for tic tac toe (255,168) -- written in JavaScript using recursion. It is not optimized, but gets you what you need. const [EMPTY, O, X] = [0, 4, 1] let count = 0 let coordinate = [ EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY ] function reducer(arr, sumOne, sumTwo = null) { let func = arr.reduce((sum, a) => sum + a, 0) if((func === sumOne) || (func === sumTwo)) return true } function checkResult() { let [a1, a2, a3, b1, b2, b3, c1, c2, c3] = coordinate if(reducer([a1,a2,a3], 3, 12)) return true if(reducer([a1,b2,c3], 3, 12)) return true if(reducer([b1,b2,b3], 3, 12)) return true if(reducer([c1,c2,c3], 3, 12)) return true if(reducer([a3,b2,c1], 3, 12)) return true if(reducer([a1,b1,c1], 3, 12)) return true if(reducer([a2,b2,c2], 3, 12)) return true if(reducer([a3,b3,c3], 3, 12)) return true if(reducer([a1,a2,a3,b1,b2,b3,c1,c2,c3], 21)) return true return false } function nextPiece() { let [countX, countO] = [0, 0] for(let i = 0; i < coordinate.length; i++) { if(coordinate[i] === X) countX++ if(coordinate[i] === O) countO++ } return countX === countO ? X : O } function countGames() { if (checkResult()) { count++ }else { for (let i = 0; i < 9; i++) { if (coordinate[i] === EMPTY) { coordinate[i] = nextPiece() countGames() coordinate[i] = EMPTY } } } } countGames() console.log(count) I separated out the checkResult returns in case you want to output various win conditions.
Could be solved with brute force but keep in mind the corner cases like player2 can't move when player1 has won and vice versa. Also remember Difference between moves of player1 and player can't be greater than 1 and less than 0. I have written code for validating whether provided combination is valid or not, might soon post on github.
Can i return list in Mathematica function?
In my code I'm trying to return list of numbers from my function but it gives me just null. sifra[zprava_, klic_] := Module[ {c, n, e, m, i, z, pocCyklu, slovo}, pocCyklu = Ceiling[Divide[StringLength[zprava], 5]]; c = Array[{}, pocCyklu]; z = Partition[Characters[zprava], 5, 5, 1, {}]; For[i = 1, i < pocCyklu + 1, i++, slovo = StringJoin # z[[i]]; m = StringToInteger[slovo]; n = klic[[1]]; e = klic[[2]]; c[[i]] = PowerMod[m, e, n]; ] Return[c] ]; sif = sifra[m, verejny] After the cycles are done there should be 2 numbers in c. Print[c] works OK it prints list with 2 elements in it but sif is null. Return[c] gives me: Null Return[{28589400926821874625642026431141504822, 2219822858062194181357669868096}]
You could write the function like this: sifra[zprava_, klic_] := Module[{c, n, e, m, i, z, pocCyklu, slovo}, pocCyklu = Ceiling[Divide[StringLength[zprava], 5]]; c = ConstantArray[{}, pocCyklu]; z = Partition[Characters[zprava], 5, 5, 1, {}]; For[i = 1, i < pocCyklu + 1, i++, slovo = StringJoin#z[[i]]; m = ToExpression[slovo]; {n, e} = klic; c[[i]] = PowerMod[m, e, n]]; c] Demonstrating use with example data: sifra["9385637605763057836503784603456", {124, 2}] {20, 97, 41, 9, 4, 113, 36} You could also write the function like this: sifra[zprava_, {n_, e_}] := Module[{z}, z = Partition[Characters[zprava], 5, 5, 1, {}]; Map[PowerMod[ToExpression[StringJoin[#]], e, n] &, z]]
Reduce array of numbers (sequence)
Imagine having an array of numbers defined as: a = [18, 20, 21, 22, 23]. I want to modify it so that it would look like this: a = [18, (20..23)]. What is the most elegant solution for that one?
Here is a code minimally modified from doc: Enumerable#slice_before. i = a[0] a.slice_before do |e| i, j = e, i j + 1 != e end .flat_map{|es| es.length < 3 ? es : es.first..es.last} # => [18, 20..23]
a = [18, 20, 21, 22, 23,13,14].sort! prev = a[0] p a.slice_before { |e| prev, prev2 = e, prev prev2 + 1 != e }.flat_map{|i| next Range.new(i.first,i.last) if i.size !=1 ; i} #=> [13..14, 18, 20..23]