Multiply Bits with factor (GLSL) - glsl

I want to have a method which multiplies each bit in a number with a factor. For example if factor is 3, each bit in the number is used three times before the next bit in the number is used.
I'm working with GLSL.

Did it with C#
private int DuplicateBitsByFactor(int value, int factor)
{
var size = sizeof(ushort) * 8;
var binaryString = new StringBuilder();
for (var i = size; i >= 0; i--)
for (var j = 0; j < factor; j++)
binaryString.Append(GetBitOnLocation(value, i));
var duplicateBitsByFactor = Convert.ToInt32(binaryString.ToString(), 2);
return duplicateBitsByFactor;
}
private int GetBitOnLocation(int value, int location)
{
return (value & (1 << location)) == 0 ? 0 : 1;
}
Any optimization?

Related

Convert uint24 to HEX string in Solidity

I am trying to convert uint24 value of a kind 0x00ff08 to a human readable string with the same characters in Solidity smart contract which I am going to deploy on RSK. In my question about bytes3 to hex string casting I was advised for these purposes to use a function
function uint24tohexstr(uint24 i) public pure returns (string memory) {
bytes memory o = new bytes(6);
uint24 mask = 0x00000f;
o[5] = bytes1(uint8tohexchar(uint8(i & mask)));
i = i >> 4;
o[4] = bytes1(uint8tohexchar(uint8(i & mask)));
i = i >> 4;
o[3] = bytes1(uint8tohexchar(uint8(i & mask)));
i = i >> 4;
o[2] = bytes1(uint8tohexchar(uint8(i & mask)));
i = i >> 4;
o[1] = bytes1(uint8tohexchar(uint8(i & mask)));
i = i >> 4;
o[0] = bytes1(uint8tohexchar(uint8(i & mask)));
return string(o);
}
I wanted to make use of a loop in that function and rewrote it like this
function uint24ToHexStr(uint24 i) public pure returns (string memory) {
bytes memory o = new bytes(6);
uint24 mask = 0x00000f; // hex 15
for(uint k = 5; k >= 0; k -= 1) {
o[k] = bytes1(uint8ToHexCharCode(uint8(i & mask)));
i >>= 4;
}
return string(o);
}
But unfortunately this function causes runtime error because on the last iteration unsigned integer k becomes -1. The first thing that crossed my mind was to increase k by one so that
for(uint k = 6; k >= 1; k -= 1) {
o[k - 1] = bytes1(uint8ToHexCharCode(uint8(i & mask)));
}
Can anyone think of a more elegant way to achieve the same result?
This line:
for(uint k = 5; k >= 0; k -= 1) {
If k is of type uint, when will k >= 0 ever evaluate to false? (hint: never)
Change k from type uint to int and problem is solved.
for(int k = 5; k >= 0; k -= 1) {
o[k] = bytes1(uint8ToHexCharCode(uint8(i & mask)));
i >>= 4;
}
Or
for(uint k = 0; k< 6; k += 1) {
o[5-k] = bytes1(uint8ToHexCharCode(uint8(i & mask)));
i >>= 4;
}
I like the 2nd option in #selbie's answer; and thought what if we used a different type of loop control structure. A regular while loop would inherit the same "final iteration uint underflow" problem that the for loop has. Switching to a do .. while loop, on the other hand, allows you to shift the evaluation of the condition from being checked before the iteration, to being checked after the iteration. This can be applied to your implementation like so:
function uint24ToHexStr(uint24 i) public pure returns (string memory) {
bytes memory o = new bytes(6);
uint24 mask = 0x00000f; // hex 15
uint k = 6;
do {
k--;
o[k] = bytes1(uint8ToHexCharCode(uint8(i & mask)));
i >>= 4;
} while (k > 0);
return string(o);
}
This avoids both the uint underflow, and also does not require k - 1 for array indices within the loop. In terms of gas cost, I would "guesstimate" that it would be close to the original implementation of the same function from the previous question. (but actually try both out and compare to confirm)
Alternative answer, also taking some inspiration from #selbie's answer of forward iteration, but instead of reversing the index order,
get the target half-byte by switching from a bitwise-and mask
to a bit-shift of 5 half-bytes (20 bits).
Like so:
function uint24ToHexStrAlt2(uint24 i) public pure returns (string memory) {
bytes memory o = new bytes(6);
uint k = 0;
do {
o[k] = bytes1(uint8ToHexCharCode(uint8(i >> 20))); // shift by 5 nibbles instead of mask
i <<= 4;
k +=1;
} while (k < 6);
return string(o);
}

Wrong output in Project Euler [duplicate]

I'm working on project euler problem number eight, in which ive been supplied this ridiculously large number:
7316717653133062491922511967442657474235534919493496983520312774506326239578318016984801869478851843858615607891129494954595017379583319528532088055111254069874715852386305071569329096329522744304355766896648950445244523161731856403098711121722383113622298934233803081353362766142828064444866452387493035890729629049156044077239071381051585930796086670172427121883998797908792274921901699720888093776657273330010533678812202354218097512545405947522435258490771167055601360483958644670632441572215539753697817977846174064955149290862569321978468622482839722413756570560574902614079729686524145351004748216637048440319989000889524345065854122758866688116427171479924442928230863465674813919123162824586178664583591245665294765456828489128831426076900422421902267105562632111110937054421750694165896040807198403850962455444362981230987879927244284909188845801561660979191338754992005240636899125607176060588611646710940507754100225698315520005593572972571636269561882670428252483600823257530420752963450
and am supposed to "Find the thirteen adjacent digits in the 1000-digit number that have the greatest product." EG the product of the first four adjacent digits is 7 * 3 * 1 * 6.
My code is the following:
int main()
{
string num = /* ridiculously large number omitted */;
int greatestProduct = 0;
int product;
for (int i=0; i < num.length() -12; i++)
{
product = ((int) num[i] - 48);
for (int j=i+1; j<i+13; j++)
{
product = product * ((int) num[j] - 48);
if (greatestProduct <= product)
{
greatestProduct = product;
}
}
}
cout << greatestProduct << endl;
}
I keep getting 2091059712 as the answer which project euler informs me is wrong and I suspect its too large anyway. Any help would be appreciated.
EDIT: changed to unsigned long int and it worked. Thanks everyone!
In fact your solution is too small rather than too big. The answer is what was pointed out in the comments, that there is integer overflow, and the clue is in the fact that your solution is close to the largest possible value for an signed int: 2147483647. You need to use a different type to store the product.
Note that the answer below is still 'correct' in that your code does do this wrong, but it's not what is causing the wrong value. Try taking your (working) code to http://codereview.stackexchange.com if you would like the folks there to tell you what you could improve in your approach and your coding style.
Previous answer
You are checking for a new greatest product inside the inner loop instead of outside. This means that your maximum includes all strings of less or equal ton 13 digits, rather than only exactly 13.
This could make a difference if you are finding a string which has fewer than 13 digits which have a large product, but a 0 at either end. You shouldn't count this as the largest, but your code does. (I haven't checked if this does actually happen.)
for (int i=0; i < num.length() -12; i++)
{
product = ((int) num[i] - 48);
for (int j=i+1; j<i+13; j++)
{
product = product * ((int) num[j] - 48);
}
if (greatestProduct <= product)
{
greatestProduct = product;
}
}
9^13 ≈ 2.54e12 (maximal possible value, needs 42 bit to be represented exactly), which doesn't fit into signed int. You should use int64.
If you don't want to mess with BigNum libraries, you could just take logarithms of your digits (rejecting 0) and add them up. It amounts to the same comparison.
A faster way without internal loop, but works only where there isn't a 0 in the input:
long long greatest(string num)
{
if (num.length() < 13)
return 0;
// Find a product of first 13 numbers.
long long product = 1;
unsigned int i;
for (i=0; i<13; ++i) {
product *= (num[i]-'0');
}
long long greatest_product = product;
// move through the large number
for (i=0; i+13<num.length(); ++i) {
product = product/(num[i]-'0')*(num[i+13]-'0');
if (greatest_product < product)
greatest_product = product;
}
return greatest_product;
}
In order to make this work with inputs containing 0, split the input string into substrings:
int main()
{
string num = /* input value*/;
long long greatest_product = 0;
size_t start = -1;
// Iterate over substrings without zero
do {
++start;
size_t end = num.find('0', start);
long long product = greatest(num.substr(start, end-start));
if (greatest_product < product)
greatest_product = product;
start = end;
} while (start != string::npos);
cout << greatest_product << endl;
}
My functional programming solution
def product(number):
product_result = 1
for n in number:
product_result *= int(n)
return product_result
length = 13
indices = range(0, len(number) - 13 + 1)
values = indices
values = map(lambda index: {"index": index, "number": number}, values)
values = map(lambda value: value["number"][value["index"]:value["index"] + length], values)
values = map(product, values)
values = max(values)
print values
public static void main(String[] args) {
String val = "7316717653133062491922511967442657474235534919493496983520312774506326239578318016984801869478851843858615607891129494954595017379583319528532088055111254069874715852386305071569329096329522744304355766896648950445244523161731856403098711121722383113622298934233803081353362766142828064444866452387493035890729629049156044077239071381051585930796086670172427121883998797908792274921901699720888093776657273330010533678812202354218097512545405947522435258490771167055601360483958644670632441572215539753697817977846174064955149290862569321978468622482839722413756570560574902614079729686524145351004748216637048440319989000889524345065854122758866688116427171479924442928230863465674813919123162824586178664583591245665294765456828489128831426076900422421902267105562632111110937054421750694165896040807198403850962455444362981230987879927244284909188845801561660979191338754992005240636899125607176060588611646710940507754100225698315520005593572972571636269561882670428252483600823257530420752963450";
int Sum = 0;
String adjacent = null;
for (int i = 0; i < val.length()-13; i++) {
int total = 1;
for (int j = 0; j < 13; j++) {
total = total * Character.getNumericValue(val.charAt(i+j));
}
if(total > Sum){
Sum = total;
adjacent = val.substring(i, i+13);
}
}
System.out.println("Sum = " + Sum);
System.out.println("Adjsc = " + adjacent );
}
I had the same problem.
int product and int greatestproduct have maximum value it can store since they are 'int' type. They can only store values up to 2147483647.
Use 'long long' type instead of 'int'.
const thousandDigit =
`73167176531330624919225119674426574742355349194934
96983520312774506326239578318016984801869478851843
85861560789112949495459501737958331952853208805511
12540698747158523863050715693290963295227443043557
66896648950445244523161731856403098711121722383113
62229893423380308135336276614282806444486645238749
30358907296290491560440772390713810515859307960866
70172427121883998797908792274921901699720888093776
65727333001053367881220235421809751254540594752243
52584907711670556013604839586446706324415722155397
53697817977846174064955149290862569321978468622482
83972241375657056057490261407972968652414535100474
82166370484403199890008895243450658541227588666881
16427171479924442928230863465674813919123162824586
17866458359124566529476545682848912883142607690042
24219022671055626321111109370544217506941658960408
07198403850962455444362981230987879927244284909188
84580156166097919133875499200524063689912560717606
05886116467109405077541002256983155200055935729725
71636269561882670428252483600823257530420752963450`;
const productsOfAdjacentNths = num =>
[...thousandDigit].reduce((acc, _, idx) => {
const nthDigitAdjX = [...thousandDigit.substr(idx, num)].reduce(
(inAcc, inCur) => inCur * inAcc,
1
);
return acc.concat(nthDigitAdjX);
}, []);
console.log(Math.max(...productsOfAdjacentNths(13))); //5377010688
This is my O(n) approach
function findLargest(digits, n){
let largest = 0;
let j = 0;
let res = 1;
for(let i = 0; i< digits.length; i ++){
res = res * parseInt(digits[i]);
if(res == 0){
res = 1;
j = 0;
continue;
}
if(j === n-1){
if(res > largest)
largest = res;
res = res/parseInt(digits[i - j]);
j = j - 1;
}
j = j + 1;
}
return largest;
}
let val = "7316717653133062491922511967442657474235534919493496983520312774506326239578318016984801869478851843858615607891129494954595017379583319528532088055111254069874715852386305071569329096329522744304355766896648950445244523161731856403098711121722383113622298934233803081353362766142828064444866452387493035890729629049156044077239071381051585930796086670172427121883998797908792274921901699720888093776657273330010533678812202354218097512545405947522435258490771167055601360483958644670632441572215539753697817977846174064955149290862569321978468622482839722413756570560574902614079729686524145351004748216637048440319989000889524345065854122758866688116427171479924442928230863465674813919123162824586178664583591245665294765456828489128831426076900422421902267105562632111110937054421750694165896040807198403850962455444362981230987879927244284909188845801561660979191338754992005240636899125607176060588611646710940507754100225698315520005593572972571636269561882670428252483600823257530420752963450";
findLargest(val, 13);
Although above solutions are good, here is a python implementation which works perfectly:
def main():
num=7316717653133062491922511967442657474235534919493496983520312774506326239578318016984801869478851843858615607891129494954595017379583319528532088055111254069874715852386305071569329096329522744304355766896648950445244523161731856403098711121722383113622298934233803081353362766142828064444866452387493035890729629049156044077239071381051585930796086670172427121883998797908792274921901699720888093776657273330010533678812202354218097512545405947522435258490771167055601360483958644670632441572215539753697817977846174064955149290862569321978468622482839722413756570560574902614079729686524145351004748216637048440319989000889524345065854122758866688116427171479924442928230863465674813919123162824586178664583591245665294765456828489128831426076900422421902267105562632111110937054421750694165896040807198403850962455444362981230987879927244284909188845801561660979191338754992005240636899125607176060588611646710940507754100225698315520005593572972571636269561882670428252483600823257530420752963450
prod,maxprod=1,0
numtostr=str(num)
length=len(numtostr)
for i in range(1,length-13+1):
prod=1
for z in range(i,i+13):
prod=prod*int(numtostr[z-1:z])
if prod>maxprod:
maxprod=prod
print "Largest 13 digit product is %d" %(maxprod)
if __name__ == '__main__':
main()
static long q8(){
long max_product = 1;
long product = 1;
String n = "LONG_INPUT";
for(int i=0;i<13;i++){
max_product *= Integer.parseInt(n.charAt(i)+"");
}
product = max_product;
for(int i=1;i<n.length()-13;i++){
int denom = Integer.parseInt(n.charAt(i-1)+"");
if(denom!=0)
product = product/denom * Integer.parseInt(n.charAt(i+12)+"");
else
product = product(i,n);
max_product = (max_product>product)?max_product:product;
}
return max_product;
}
static long product(int index,String n){
long pro = 1;
for(int i=index;i<index+13;i++){
pro *= Integer.parseInt(n.charAt(i)+"");
}
return pro;
}
Try this:
{
DateTime BeganAt = new DateTime();
BeganAt = DateTime.Now;
Int64 result = 0;
string testNumber = "7316717653133062491922511967442657474235534919493496983520312774506326239578318016984801869478851843858615607891129494954595017379583319528532088055111254069874715852386305071569329096329522744304355766896648950445244523161731856403098711121722383113622298934233803081353362766142828064444866452387493035890729629049156044077239071381051585930796086670172427121883998797908792274921901699720888093776657273330010533678812202354218097512545405947522435258490771167055601360483958644670632441572215539753697817977846174064955149290862569321978468622482839722413756570560574902614079729686524145351004748216637048440319989000889524345065854122758866688116427171479924442928230863465674813919123162824586178664583591245665294765456828489128831426076900422421902267105562632111110937054421750694165896040807198403850962455444362981230987879927244284909188845801561660979191338754992005240636899125607176060588611646710940507754100225698315520005593572972571636269561882670428252483600823257530420752963450";
StringBuilder StringBuilder = new StringBuilder(13);
Int64 maxNumber = 0;
try
{
char[] numbers = testNumber.ToCharArray();
int tempCounter = 13;
for (int i = 0;i < numbers.Length;i++)
{
if(i < tempCounter)
{
StringBuilder.Append(numbers[i]);
}
else if (i == tempCounter)
{
if (maxNumber < Convert.ToInt64(StringBuilder.ToString()))
{
maxNumber = Convert.ToInt64(StringBuilder.ToString());
}
StringBuilder.Clear();
StringBuilder.Append(numbers[i]);
tempCounter = tempCounter + n;
}
}
result = maxNumber;
}
catch
{
throw;
}
DateTime EndedAt = new DateTime();
EndedAt = DateTime.Now;
TimeSpan TimeItTook = (EndedAt - BeganAt);
return Convert.ToString(result) + " - Time took to execute: " + Convert.ToString(TimeItTook.TotalMilliseconds);
}
long long int sum = 1,high=0;
for (int i = 0; i < 988; i++)
{
sum = sum*(arr[i] - 48);
for (int j = i + 1; j < i+13; j++)
{
sum = sum*(arr[j]-48);
}
if (sum >= high)
{
high = sum;
}
sum = 1;
}
My solution to above problem if someone is still watching this in 2018.Although there are lots of solution to this question here my solution pre-checks the individual 13 digits which have a 0 in them.As something multiplied with 0 is always 0 so we can remove this useless computation
int j = 0, k = 12;
long long int mult = 1;
long long int max = 0;
char *digits = /*Big number*/
while(k < 1000){
for (int i = j; i <= k; ++i)
{
/* code */
long long int val = digits[i] -'0';
/* check if any number in series contains 0 */
if(val == 0){
break;
}
mult = mult * val;
}
printf("mult is %lld\n",mult );
/* check for max value */
if(max < mult){
max = mult;
}
printf("the new max is %lld\n", max);
j += 1;
k += 1;
mult = 1;
printf("%d iteration finished\n", k);
}
printf("%lld\n", max);
You should use 'int64_t' at the place of 'int'
I have solve this problem using python 're' module
Finding all possible 13 digits number without having zeros (total 988 with zero and 283 without zero) then find the product of each of these digits and check for max
here i have used look ahead regex
Note: string must not contain any newline char
s = '731671765...'
import re
def product_13(d):
pro = 1
while d:
pro *= d % 10
d //= 10
return pro
pat = re.compile(r'(?=([1-9]{13}))')
all = map(int, re.findall(pat, s))
pro = -1
for i in all:
v = product_13(i)
if pro < v:
pro = v
print(pro)
**This is JavaScript solution.**
greatestProductOfAdjacentDigit = (givenNumber, noOfDigit) => {
stringNumberToNumbers = givenNumber => givenNumber.split('').map(each => parseInt(each, 10))
let numbers = mathematicalProblems.stringNumberToNumbers(givenNumber);
return numbers.map(function (each, ind, arr) {
return mathematicalProblems.productOfAll(arr.slice(ind, ind + noOfDigit));
}).reduce(function (accumulator, currentValue) {
return accumulator > currentValue ? accumulator : currentValue;
});
};
Testing
const givenNumber = '73167176531330624919225119674426574742355349' +
'194934969835203127745063262395783180169848018694788518438586' +
'156078911294949545950173795833195285320880551112540698747158' +
'523863050715693290963295227443043557668966489504452445231617' +
'318564030987111217223831136222989342338030813533627661428280' +
'644448664523874930358907296290491560440772390713810515859307' +
'960866701724271218839987979087922749219016997208880937766572' +
'733300105336788122023542180975125454059475224352584907711670' +
'556013604839586446706324415722155397536978179778461740649551' +
'492908625693219784686224828397224137565705605749026140797296' +
'865241453510047482166370484403199890008895243450658541227588' +
'666881164271714799244429282308634656748139191231628245861786' +
'645835912456652947654568284891288314260769004224219022671055' +
'626321111109370544217506941658960408071984038509624554443629' +
'812309878799272442849091888458015616609791913387549920052406' +
'368991256071760605886116467109405077541002256983155200055935' +
'72972571636269561882670428252483600823257530420752963450';
console.log(greatestProductOfAdjacentDigit(givenNumber, 4)); //5832
console.log(greatestProductOfAdjacentDigit(givenNumber, 13)); //23514624000
My 2 cents ... Javascript
Largest_product_in_series_13 = g => {
return [...g.matchAll(/(?=([1-9]{13}))/g)]
.reduce((a,c)=>(p=eval(c[1].split``.join`*`),p>a?p:a),0)
}
First it matches all 13 digit series, then it reduces to the biggest product.
console.log(Largest_product_in_series_13(`7316717653133062491922....
> 23514624000
start: 14.292ms
I solved it using ruby. if
x = "7316717653133062491922511967442657474235534919493496983520312774506326239578318016984801869478851843858615607891129494954595017379583319528532088055111254069874715852386305071569329096329522744304355766896648950445244523161731856403098711121722383113622298934233803081353362766142828064444866452387493035890729629049156044077239071381051585930796086670172427121883998797908792274921901699720888093776657273330010533678812202354218097512545405947522435258490771167055601360483958644670632441572215539753697817977846174064955149290862569321978468622482839722413756570560574902614079729686524145351004748216637048440319989000889524345065854122758866688116427171479924442928230863465674813919123162824586178664583591245665294765456828489128831426076900422421902267105562632111110937054421750694165896040807198403850962455444362981230987879927244284909188845801561660979191338754992005240636899125607176060588611646710940507754100225698315520005593572972571636269561882670428252483600823257530420752963450"
then used below logic to solve the problem
def print_lps(x)
p = 1
0.upto(x.length-13) do |i|
j = i
xy = 1
while j < i+13 do
xy *= x[j].to_i
j += 1
end
p = xy if xy > p
end
puts p
end
print_lps(x) # 23514624000
I solve the problem using this approach
1.Run two loops first outer loop which iterate over numbers in the string.
2.Inner loop reach to next 13 numbers afterwards and store its product in a variable
3.As inner loop ends we only use maximum value.(that what we need) :>
Have a look at my code in C++
#include <bits/stdc++.h>
using namespace std;
int main()
{
string s="//thestring is there";
long long unsigned mainans=1,ans=1; //initialize the value of mainans and ans to 1 (not 0 as product also become 0)
for(int i=0;i<s.length()-13;i++) //run the loop from 0 upto 13 minus string length
{
ans=1;
for(int j=i;j<i+13;j++) //now from that particular digit we check 13 digits afterwards it
{
int m=s[j]-'0'; //convert the number from string to integer
ans*=m; //taking product in every interation for 13 digits
}
mainans=max(mainans,ans); //now taking only max value because that what we need
}
cout<<mainans;
return 0;
}
This will find the answer in O(n) time and it handles zero. Written in Dart.
/**
* Main function
*
* Find the thirteen adjacent digits in the 1000-digit number that have the greatest product.
* What is the value of this product?
*
*/
const String DIGITS = "73167176531330624919225119674426574742355349194934"
"96983520312774506326239578318016984801869478851843"
"85861560789112949495459501737958331952853208805511"
"12540698747158523863050715693290963295227443043557"
"66896648950445244523161731856403098711121722383113"
"62229893423380308135336276614282806444486645238749"
"30358907296290491560440772390713810515859307960866"
"70172427121883998797908792274921901699720888093776"
"65727333001053367881220235421809751254540594752243"
"52584907711670556013604839586446706324415722155397"
"53697817977846174064955149290862569321978468622482"
"83972241375657056057490261407972968652414535100474"
"82166370484403199890008895243450658541227588666881"
"16427171479924442928230863465674813919123162824586"
"17866458359124566529476545682848912883142607690042"
"24219022671055626321111109370544217506941658960408"
"07198403850962455444362981230987879927244284909188"
"84580156166097919133875499200524063689912560717606"
"05886116467109405077541002256983155200055935729725"
"71636269561882670428252483600823257530420752963450";
main(List<String> args) {
const int MAX_DIGITS = 13;
int len = DIGITS.length;
int digits = 0;
int largest = 0;
int current = 0;
int index = 0;
while (index < len) {
int value = int.parse(DIGITS[index]);
// if we get a zero then rebuild the MAX_DIGITS consecutive digits
if (value == 0) {
current = 0;
digits = 0;
} else {
// Multiply consecutive digits up to target set
if (digits < MAX_DIGITS) {
if (current == 0) {
current = value;
} else
current *= value;
digits++;
} else {
int divisor = int.parse(DIGITS[index - MAX_DIGITS]);
if (current == 0) {
current = value;
} else {
current = (current ~/ divisor);
current *= value;
}
}
if (current > largest) {
largest = current;
}
}
index++;
}
print('Num $largest');
}

Codility MinAbsSum

I tried this Codility test: MinAbsSum.
https://codility.com/programmers/lessons/17-dynamic_programming/min_abs_sum/
I solved the problem by searching the whole tree of possibilities. The results were OK, however, my solution failed due to timeout for large input. In other words the time complexity was not as good as expected. My solution is O(nlogn), something normal with trees. But this coding test was in the section "Dynamic Programming", and there must be some way to improve it. I tried with summing the whole set first and then using this information, but always there is something missing in my solution. Does anybody have an idea on how to improve my solution using DP?
#include <vector>
using namespace std;
int sum(vector<int>& A, size_t i, int s)
{
if (i == A.size())
return s;
int tmpl = s + A[i];
int tmpr = s - A[i];
return min (abs(sum(A, i+1, tmpl)), abs(sum(A, i+1, tmpr)));
}
int solution(vector<int> &A) {
return sum(A, 0, 0);
}
I could not solve it. But here's the official answer.
Quoting it:
Notice that the range of numbers is quite small (maximum 100). Hence,
there must be a lot of duplicated numbers. Let count[i] denote the
number of occurrences of the value i. We can process all occurrences
of the same value at once. First we calculate values count[i] Then we
create array dp such that:
dp[j] = −1 if we cannot get the sum j,
dp[j] >= ­ 0 if we can get sum j.
Initially, dp[j] = -1 for all of j (except dp[0] = 0). Then we scan
through all the values a appearing in A; we consider all a such
that count[a]>0. For every such a we update dp that dp[j] denotes
how many values a remain (maximally) after achieving sum j. Note
that if the previous value at dp[j] >= 0 then we can set dp[j] =
count[a] as no value a is needed to obtain the sum j. Otherwise we
must obtain sum j-a first and then use a number a to get sum j. In
such a situation dp[j] = dp[j-a]-1. Using this algorithm, we can
mark all the sum values and choose the best one (closest to half of S,
the sum of abs of A).
def MinAbsSum(A):
N = len(A)
M = 0
for i in range(N):
A[i] = abs(A[i])
M = max(A[i], M)
S = sum(A)
count = [0] * (M + 1)
for i in range(N):
count[A[i]] += 1
dp = [-1] * (S + 1)
dp[0] = 0
for a in range(1, M + 1):
if count[a] > 0:
for j in range(S):
if dp[j] >= 0:
dp[j] = count[a]
elif (j >= a and dp[j - a] > 0):
dp[j] = dp[j - a] - 1
result = S
for i in range(S // 2 + 1):
if dp[i] >= 0:
result = min(result, S - 2 * i)
return result
(note that since the final iteration only considers sums up until S // 2 + 1, we can save some space and time by only creating a DP Cache up until that value as well)
The Java answer provided by fladam returns wrong result for input [2, 3, 2, 2, 3], although it gets 100% score.
Java Solution
import java.util.Arrays;
public class MinAbsSum{
static int[] dp;
public static void main(String args[]) {
int[] array = {1, 5, 2, -2};
System.out.println(findMinAbsSum(array));
}
public static int findMinAbsSum(int[] A) {
int arrayLength = A.length;
int M = 0;
for (int i = 0; i < arrayLength; i++) {
A[i] = Math.abs(A[i]);
M = Math.max(A[i], M);
}
int S = sum(A);
dp = new int[S + 1];
int[] count = new int[M + 1];
for (int i = 0; i < arrayLength; i++) {
count[A[i]] += 1;
}
Arrays.fill(dp, -1);
dp[0] = 0;
for (int i = 1; i < M + 1; i++) {
if (count[i] > 0) {
for(int j = 0; j < S; j++) {
if (dp[j] >= 0) {
dp[j] = count[i];
} else if (j >= i && dp[j - i] > 0) {
dp[j] = dp[j - i] - 1;
}
}
}
}
int result = S;
for (int i = 0; i < Math.floor(S / 2) + 1; i++) {
if (dp[i] >= 0) {
result = Math.min(result, S - 2 * i);
}
}
return result;
}
public static int sum(int[] array) {
int sum = 0;
for(int i : array) {
sum += i;
}
return sum;
}
}
I invented another solution, better than the previous one. I do not use recursion any more.
This solution works OK (all logical tests passed), and also passed some of the performance tests, but not all. How else can I improve it?
#include <vector>
#include <set>
using namespace std;
int solution(vector<int> &A) {
if (A.size() == 0) return 0;
set<int> sums, tmpSums;
sums.insert(abs(A[0]));
for (auto it = begin(A) + 1; it != end(A); ++it)
{
for (auto s : sums)
{
tmpSums.insert(abs(s + abs(*it)));
tmpSums.insert(abs(s - abs(*it)));
}
sums = tmpSums;
tmpSums.clear();
}
return *sums.begin();
}
This solution (in Java) scored 100% for both (correctness and performance)
public int solution(int[] a){
if (a.length == 0) return 0;
if (a.length == 1) return a[0];
int sum = 0;
for (int i=0;i<a.length;i++){
sum += Math.abs(a[i]);
}
int[] indices = new int[a.length];
indices[0] = 0;
int half = sum/2;
int localSum = Math.abs(a[0]);
int minLocalSum = Integer.MAX_VALUE;
int placeIndex = 1;
for (int i=1;i<a.length;i++){
if (localSum<half){
if (Math.abs(2*minLocalSum-sum) > Math.abs(2*localSum - sum))
minLocalSum = localSum;
localSum += Math.abs(a[i]);
indices[placeIndex++] = i;
}else{
if (localSum == half)
return Math.abs(2*half - sum);
if (Math.abs(2*minLocalSum-sum) > Math.abs(2*localSum - sum))
minLocalSum = localSum;
if (placeIndex > 1) {
localSum -= Math.abs(a[indices[placeIndex--]]);
i = indices[placeIndex];
}
}
}
return (Math.abs(2*minLocalSum - sum));
}
this solution treats all elements like they are positive numbers and it's looking to reach as close as it can to the sum of all elements divided by 2 (in that case we know that the sum of all other elements will be the same delta far from the half too -> abs sum will be minimum possible ).
it does so by starting with the first element and successively adding others to the "local" sum (and recording indices of elements in the sum) until it reaches sum of x >= sumAll/2. if that x is equal to sumAll/2 we have an optimal solution. if not, we go step back in the indices array and continue picking other element where last iteration in that position ended. the result will be a "local" sum having abs((sumAll - sum) - sum) closest to 0;
fixed solution:
public static int solution(int[] a){
if (a.length == 0) return 0;
if (a.length == 1) return a[0];
int sum = 0;
for (int i=0;i<a.length;i++) {
a[i] = Math.abs(a[i]);
sum += a[i];
}
Arrays.sort(a);
int[] arr = a;
int[] arrRev = new int[arr.length];
int minRes = Integer.MAX_VALUE;
for (int t=0;t<=4;t++) {
arr = fold(arr);
int res1 = findSum(arr, sum);
if (res1 < minRes) minRes = res1;
rev(arr, arrRev);
int res2 = findSum(arrRev, sum);
if (res2 < minRes) minRes = res2;
arrRev = fold(arrRev);
int res3 = findSum(arrRev, sum);
if (res3 < minRes) minRes = res3;
}
return minRes;
}
private static void rev(int[] arr, int[] arrRev){
for (int i = 0; i < arrRev.length; i++) {
arrRev[i] = arr[arr.length - 1 - i];
}
}
private static int[] fold(int[] a){
int[] arr = new int[a.length];
for (int i=0;a.length/2+i/2 < a.length && a.length/2-i/2-1 >= 0;i+=2){
arr[i] = a[a.length/2+i/2];
arr[i+1] = a[a.length/2-i/2-1];
}
if (a.length % 2 > 0) arr[a.length-1] = a[a.length-1];
else{
arr[a.length-2] = a[0];
arr[a.length-1] = a[a.length-1];
}
return arr;
}
private static int findSum(int[] arr, int sum){
int[] indices = new int[arr.length];
indices[0] = 0;
double half = Double.valueOf(sum)/2;
int localSum = Math.abs(arr[0]);
int minLocalSum = Integer.MAX_VALUE;
int placeIndex = 1;
for (int i=1;i<arr.length;i++){
if (localSum == half)
return 2*localSum - sum;
if (Math.abs(2*minLocalSum-sum) > Math.abs(2*localSum - sum))
minLocalSum = localSum;
if (localSum<half){
localSum += Math.abs(arr[i]);
indices[placeIndex++] = i;
}else{
if (placeIndex > 1) {
localSum -= Math.abs(arr[indices[--placeIndex]]);
i = indices[placeIndex];
}
}
}
return Math.abs(2*minLocalSum - sum);
}
The following is a rendering of the official answer in C++ (scoring 100% in task, correctness, and performance):
#include <cmath>
#include <algorithm>
#include <numeric>
using namespace std;
int solution(vector<int> &A) {
// write your code in C++14 (g++ 6.2.0)
const int N = A.size();
int M = 0;
for (int i=0; i<N; i++) {
A[i] = abs(A[i]);
M = max(M, A[i]);
}
int S = accumulate(A.begin(), A.end(), 0);
vector<int> counts(M+1, 0);
for (int i=0; i<N; i++) {
counts[A[i]]++;
}
vector<int> dp(S+1, -1);
dp[0] = 0;
for (int a=1; a<M+1; a++) {
if (counts[a] > 0) {
for (int j=0; j<S; j++) {
if (dp[j] >= 0) {
dp[j] = counts[a];
} else if ((j >= a) && (dp[j-a] > 0)) {
dp[j] = dp[j-a]-1;
}
}
}
}
int result = S;
for (int i =0; i<(S/2+1); i++) {
if (dp[i] >= 0) {
result = min(result, S-2*i);
}
}
return result;
}
You are almost 90% to the actual solution. It seems you understand recursion very well. Now, You should apply dynamic programming here with your program.
Dynamic Programming is nothing but memoization to the recursion so that we will not calculate same sub problems again and again. If same sub problems encounter , we return the previously calculated and memorized value. Memorization can be done with the help of a 2D array , say dp[][], where first state represent current index of array and second state represent summation.
For this problem specific, instead of giving calls to both states from each state, you sometimes can greedily take decision to skip one call.
I would like to provide the algorithm and then my implementation in C++. Idea is more or less the same as the official codility solution with some constant optimisation added.
Calculate the maximum absolute element of the inputs.
Calculate the absolute sum of the inputs.
Count the number of occurrence of each number in the inputs. Store the results in a vector hash.
Go through each input.
For each input, goes through all possible sums of any number of inputs. It is a slight constant optimisation to go only up to half of the possible sums.
For each sum that has been made before, set the occurrence count of the current input.
Check for each potential sum equal to or greater than the current input whether this input has already been used before. Update the values at the current sum accordingly. We do not need to check for potential sums less than the current input in this iteration, since it is evident that it has not been used before.
The above nested loop will fill in each possible sum with a value greater than -1.
Go through this possible sum hash again to look for the closest sum to half that is possible to make. Eventually, the min abs sum will be the difference of this from the half multiplied by two as the difference will be added up in both groups as the difference from the median.
The runtime complexity of this algorithm is O(N * max(abs(A)) ^ 2), or simply O(N * M ^ 2). That is because the outer loop is iterating M times and the inner loop is iterating sum times. The sum is basically N * M in worst case. Therefore, it is O(M * N * M).
The space complexity of this solution is O(N * M) because we allocate a hash of N items for the counts and a hash of S items for the sums. S is N * M again.
int solution(vector<int> &A)
{
int M = 0, S = 0;
for (const int e : A) { M = max(abs(e), M); S += abs(e); }
vector<int> counts(M + 1, 0);
for (const int e : A) { ++counts[abs(e)]; }
vector<int> sums(S + 1, -1);
sums[0] = 0;
for (int ci = 1; ci < counts.size(); ++ci) {
if (!counts[ci]) continue;
for (int si = 0; si < S / 2 + 1; ++si) {
if (sums[si] >= 0) sums[si] = counts[ci];
else if (si >= ci and sums[si - ci] > 0) sums[si] = sums[si - ci] - 1;
}
}
int min_abs_sum = S;
for (int i = S / 2; i >= 0; --i) if (sums[i] >= 0) return S - 2 * i;
return min_abs_sum;
}
Let me add my 50 cent, how to come up with the score 100% solution.
For me it was hard to understand the ultimate solution, proposed earlier in this thread.
So I started with warm-up solution with score 63%, because its O(NxNxM),
and because it doesn't use the fact that M is quite small value, and there are many duplicates in big arrays
here the key part is to understand how array isSumPossible is filled and interpreted:
how to fill array isSumPossible using numbers in input array:
if isSumPossible[sum] >= 0, i.e. sum is already possible, even without current number, then let's set it's value to 1 - count of current number, that is left unused for this sum, it'll go to our "reserve", so we can use it later for greater sums.
if (isSumPossible[sum] >= 0) {
isSumPossible[sum] = 1;
}
if isSumPossible[sum] <= 0, i.e. sum is considered not yet possible, with all input numbers considered previously, then let's check maybe
smaller sum sum - number is already considered as possible, and we have in "reserve" our current number (isSumPossible[sum - number] == 1), then do following
else if (sum >= number && isSumPossible[sum - number] == 1) {
isSumPossible[sum] = 0;
}
here isSumPossible[sum] = 0 means that we have used number in composing sum and it's now considered as possible (>=0), but we have no number in "reserve", because we've used it ( =0)
how to interpret filled array isSumPossible after considering all numbers in input array:
if isSumPossible[sum] >= 0 then the sum is possible, i.e. it can be reached by summation of some numbers in given array
if isSumPossible[sum] < 0 then the sum can't be reached by summation of any numbers in given array
The more simple thing here is to understand why we are searching sums only in interval [0, maxSum/2]:
because if find a possible sum, that is very close to maxSum/2,
ideal case here if we've found possible sum = maxSum/2,
if so, then it's obvious, that we can somehow use the rest numbers in input array to make another maxSum/2, but now with negative sign, so as a result of annihilation we'll get solution = 0, because maxSum/2 + (-1)maxSum/2 = 0.
But 0 the best case solution, not always reachable.
But we, nevertheless, should seek for the minimal delta = ((maxSum - sum) - sum),
so this we seek for delta -> 0, that's why we have this:
int result = Integer.MAX_VALUE;
for (int sum = 0; sum < maxSum / 2 + 1; sum++) {
if (isSumPossible[sum] >= 0) {
result = Math.min(result, (maxSum - sum) - sum);
}
}
warm-up solution
public int solution(int[] A) {
if (A == null || A.length == 0) {
return 0;
}
if (A.length == 1) {
return A[0];
}
int maxSum = 0;
for (int i = 0; i < A.length; i++) {
A[i] = Math.abs(A[i]);
maxSum += A[i];
}
int[] isSumPossible = new int[maxSum + 1];
Arrays.fill(isSumPossible, -1);
isSumPossible[0] = 0;
for (int number : A) {
for (int sum = 0; sum < maxSum / 2 + 1; sum++) {
if (isSumPossible[sum] >= 0) {
isSumPossible[sum] = 1;
} else if (sum >= number && isSumPossible[sum - number] == 1) {
isSumPossible[sum] = 0;
}
}
}
int result = Integer.MAX_VALUE;
for (int sum = 0; sum < maxSum / 2 + 1; sum++) {
if (isSumPossible[sum] >= 0) {
result = Math.min(result, maxSum - 2 * sum);
}
}
return result;
}
and after this we can optimize it, using the fact that there are many duplicate numbers in big arrays, and we come up with the solution with 100% score, its O(Mx(NxM)), because maxSum = NxM at worst case
public int solution(int[] A) {
if (A == null || A.length == 0) {
return 0;
}
if (A.length == 1) {
return A[0];
}
int maxNumber = 0;
int maxSum = 0;
for (int i = 0; i < A.length; i++) {
A[i] = Math.abs(A[i]);
maxNumber = Math.max(maxNumber, A[i]);
maxSum += A[i];
}
int[] count = new int[maxNumber + 1];
for (int i = 0; i < A.length; i++) {
count[A[i]]++;
}
int[] isSumPossible = new int[maxSum + 1];
Arrays.fill(isSumPossible, -1);
isSumPossible[0] = 0;
for (int number = 0; number < maxNumber + 1; number++) {
if (count[number] > 0) {
for (int sum = 0; sum < maxSum / 2 + 1; sum++) {
if (isSumPossible[sum] >= 0) {
isSumPossible[sum] = count[number];
} else if (sum >= number && isSumPossible[sum - number] > 0) {
isSumPossible[sum] = isSumPossible[sum - number] - 1;
}
}
}
}
int result = Integer.MAX_VALUE;
for (int sum = 0; sum < maxSum / 2 + 1; sum++) {
if (isSumPossible[sum] >= 0) {
result = Math.min(result, maxSum - 2 * sum);
}
}
return result;
}
I hope I've made it at least a little clear
Kotlin solution
Time complexity: O(N * max(abs(A))**2)
Score: 100%
import kotlin.math.*
fun solution(A: IntArray): Int {
val N = A.size
var M = 0
for (i in 0 until N) {
A[i] = abs(A[i])
M = max(M, A[i])
}
val S = A.sum()
val counts = MutableList(M + 1) { 0 }
for (i in 0 until N) {
counts[A[i]]++
}
val dp = MutableList(S + 1) { -1 }
dp[0] = 0
for (a in 1 until M + 1) {
if (counts[a] > 0) {
for (j in 0 until S) {
if (dp[j] >= 0) {
dp[j] = counts[a]
} else if (j >= a && dp[j - a] > 0) {
dp[j] = dp[j - a] - 1
}
}
}
}
var result = S
for (i in 0 until (S / 2 + 1)) {
if (dp[i] >= 0) {
result = minOf(result, S - 2 * i)
}
}
return result
}

How to get the lexical rank of a string? [duplicate]

I'm posting this although much has already been posted about this question. I didn't want to post as an answer since it's not working. The answer to this post (Finding the rank of the Given string in list of all possible permutations with Duplicates) did not work for me.
So I tried this (which is a compilation of code I've plagiarized and my attempt to deal with repetitions). The non-repeating cases work fine. BOOKKEEPER generates 83863, not the desired 10743.
(The factorial function and letter counter array 'repeats' are working correctly. I didn't post to save space.)
while (pointer != length)
{
if (sortedWordChars[pointer] != wordArray[pointer])
{
// Swap the current character with the one after that
char temp = sortedWordChars[pointer];
sortedWordChars[pointer] = sortedWordChars[next];
sortedWordChars[next] = temp;
next++;
//For each position check how many characters left have duplicates,
//and use the logic that if you need to permute n things and if 'a' things
//are similar the number of permutations is n!/a!
int ct = repeats[(sortedWordChars[pointer]-64)];
// Increment the rank
if (ct>1) { //repeats?
System.out.println("repeating " + (sortedWordChars[pointer]-64));
//In case of repetition of any character use: (n-1)!/(times)!
//e.g. if there is 1 character which is repeating twice,
//x* (n-1)!/2!
int dividend = getFactorialIter(length - pointer - 1);
int divisor = getFactorialIter(ct);
int quo = dividend/divisor;
rank += quo;
} else {
rank += getFactorialIter(length - pointer - 1);
}
} else
{
pointer++;
next = pointer + 1;
}
}
Note: this answer is for 1-based rankings, as specified implicitly by example. Here's some Python that works at least for the two examples provided. The key fact is that suffixperms * ctr[y] // ctr[x] is the number of permutations whose first letter is y of the length-(i + 1) suffix of perm.
from collections import Counter
def rankperm(perm):
rank = 1
suffixperms = 1
ctr = Counter()
for i in range(len(perm)):
x = perm[((len(perm) - 1) - i)]
ctr[x] += 1
for y in ctr:
if (y < x):
rank += ((suffixperms * ctr[y]) // ctr[x])
suffixperms = ((suffixperms * (i + 1)) // ctr[x])
return rank
print(rankperm('QUESTION'))
print(rankperm('BOOKKEEPER'))
Java version:
public static long rankPerm(String perm) {
long rank = 1;
long suffixPermCount = 1;
java.util.Map<Character, Integer> charCounts =
new java.util.HashMap<Character, Integer>();
for (int i = perm.length() - 1; i > -1; i--) {
char x = perm.charAt(i);
int xCount = charCounts.containsKey(x) ? charCounts.get(x) + 1 : 1;
charCounts.put(x, xCount);
for (java.util.Map.Entry<Character, Integer> e : charCounts.entrySet()) {
if (e.getKey() < x) {
rank += suffixPermCount * e.getValue() / xCount;
}
}
suffixPermCount *= perm.length() - i;
suffixPermCount /= xCount;
}
return rank;
}
Unranking permutations:
from collections import Counter
def unrankperm(letters, rank):
ctr = Counter()
permcount = 1
for i in range(len(letters)):
x = letters[i]
ctr[x] += 1
permcount = (permcount * (i + 1)) // ctr[x]
# ctr is the histogram of letters
# permcount is the number of distinct perms of letters
perm = []
for i in range(len(letters)):
for x in sorted(ctr.keys()):
# suffixcount is the number of distinct perms that begin with x
suffixcount = permcount * ctr[x] // (len(letters) - i)
if rank <= suffixcount:
perm.append(x)
permcount = suffixcount
ctr[x] -= 1
if ctr[x] == 0:
del ctr[x]
break
rank -= suffixcount
return ''.join(perm)
If we use mathematics, the complexity will come down and will be able to find rank quicker. This will be particularly helpful for large strings.
(more details can be found here)
Suggest to programmatically define the approach shown here (screenshot attached below) given below)
I would say David post (the accepted answer) is super cool. However, I would like to improve it further for speed. The inner loop is trying to find inverse order pairs, and for each such inverse order, it tries to contribute to the increment of rank. If we use an ordered map structure (binary search tree or BST) in that place, we can simply do an inorder traversal from the first node (left-bottom) until it reaches the current character in the BST, rather than traversal for the whole map(BST). In C++, std::map is a perfect one for BST implementation. The following code reduces the necessary iterations in loop and removes the if check.
long long rankofword(string s)
{
long long rank = 1;
long long suffixPermCount = 1;
map<char, int> m;
int size = s.size();
for (int i = size - 1; i > -1; i--)
{
char x = s[i];
m[x]++;
for (auto it = m.begin(); it != m.find(x); it++)
rank += suffixPermCount * it->second / m[x];
suffixPermCount *= (size - i);
suffixPermCount /= m[x];
}
return rank;
}
#Dvaid Einstat, this was really helpful. It took me a WHILE to figure out what you were doing as I am still learning my first language(C#). I translated it into C# and figured that I'd give that solution as well since this listing helped me so much!
Thanks!
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Text.RegularExpressions;
namespace CsharpVersion
{
class Program
{
//Takes in the word and checks to make sure that the word
//is between 1 and 25 charaters inclusive and only
//letters are used
static string readWord(string prompt, int high)
{
Regex rgx = new Regex("^[a-zA-Z]+$");
string word;
string result;
do
{
Console.WriteLine(prompt);
word = Console.ReadLine();
} while (word == "" | word.Length > high | rgx.IsMatch(word) == false);
result = word.ToUpper();
return result;
}
//Creates a sorted dictionary containing distinct letters
//initialized with 0 frequency
static SortedDictionary<char,int> Counter(string word)
{
char[] wordArray = word.ToCharArray();
int len = word.Length;
SortedDictionary<char,int> count = new SortedDictionary<char,int>();
foreach(char c in word)
{
if(count.ContainsKey(c))
{
}
else
{
count.Add(c, 0);
}
}
return count;
}
//Creates a factorial function
static int Factorial(int n)
{
if (n <= 1)
{
return 1;
}
else
{
return n * Factorial(n - 1);
}
}
//Ranks the word input if there are no repeated charaters
//in the word
static Int64 rankWord(char[] wordArray)
{
int n = wordArray.Length;
Int64 rank = 1;
//loops through the array of letters
for (int i = 0; i < n-1; i++)
{
int x=0;
//loops all letters after i and compares them for factorial calculation
for (int j = i+1; j<n ; j++)
{
if (wordArray[i] > wordArray[j])
{
x++;
}
}
rank = rank + x * (Factorial(n - i - 1));
}
return rank;
}
//Ranks the word input if there are repeated charaters
//in the word
static Int64 rankPerm(String word)
{
Int64 rank = 1;
Int64 suffixPermCount = 1;
SortedDictionary<char, int> counter = Counter(word);
for (int i = word.Length - 1; i > -1; i--)
{
char x = Convert.ToChar(word.Substring(i,1));
int xCount;
if(counter[x] != 0)
{
xCount = counter[x] + 1;
}
else
{
xCount = 1;
}
counter[x] = xCount;
foreach (KeyValuePair<char,int> e in counter)
{
if (e.Key < x)
{
rank += suffixPermCount * e.Value / xCount;
}
}
suffixPermCount *= word.Length - i;
suffixPermCount /= xCount;
}
return rank;
}
static void Main(string[] args)
{
Console.WriteLine("Type Exit to end the program.");
string prompt = "Please enter a word using only letters:";
const int MAX_VALUE = 25;
Int64 rank = new Int64();
string theWord;
do
{
theWord = readWord(prompt, MAX_VALUE);
char[] wordLetters = theWord.ToCharArray();
Array.Sort(wordLetters);
bool duplicate = false;
for(int i = 0; i< theWord.Length - 1; i++)
{
if(wordLetters[i] < wordLetters[i+1])
{
duplicate = true;
}
}
if(duplicate)
{
SortedDictionary<char, int> counter = Counter(theWord);
rank = rankPerm(theWord);
Console.WriteLine("\n" + theWord + " = " + rank);
}
else
{
char[] letters = theWord.ToCharArray();
rank = rankWord(letters);
Console.WriteLine("\n" + theWord + " = " + rank);
}
} while (theWord != "EXIT");
Console.WriteLine("\nPress enter to escape..");
Console.Read();
}
}
}
If there are k distinct characters, the i^th character repeated n_i times, then the total number of permutations is given by
(n_1 + n_2 + ..+ n_k)!
------------------------------------------------
n_1! n_2! ... n_k!
which is the multinomial coefficient.
Now we can use this to compute the rank of a given permutation as follows:
Consider the first character(leftmost). say it was the r^th one in the sorted order of characters.
Now if you replace the first character by any of the 1,2,3,..,(r-1)^th character and consider all possible permutations, each of these permutations will precede the given permutation. The total number can be computed using the above formula.
Once you compute the number for the first character, fix the first character, and repeat the same with the second character and so on.
Here's the C++ implementation to your question
#include<iostream>
using namespace std;
int fact(int f) {
if (f == 0) return 1;
if (f <= 2) return f;
return (f * fact(f - 1));
}
int solve(string s,int n) {
int ans = 1;
int arr[26] = {0};
int len = n - 1;
for (int i = 0; i < n; i++) {
s[i] = toupper(s[i]);
arr[s[i] - 'A']++;
}
for(int i = 0; i < n; i++) {
int temp = 0;
int x = 1;
char c = s[i];
for(int j = 0; j < c - 'A'; j++) temp += arr[j];
for (int j = 0; j < 26; j++) x = (x * fact(arr[j]));
arr[c - 'A']--;
ans = ans + (temp * ((fact(len)) / x));
len--;
}
return ans;
}
int main() {
int i,n;
string s;
cin>>s;
n=s.size();
cout << solve(s,n);
return 0;
}
Java version of unrank for a String:
public static String unrankperm(String letters, int rank) {
Map<Character, Integer> charCounts = new java.util.HashMap<>();
int permcount = 1;
for(int i = 0; i < letters.length(); i++) {
char x = letters.charAt(i);
int xCount = charCounts.containsKey(x) ? charCounts.get(x) + 1 : 1;
charCounts.put(x, xCount);
permcount = (permcount * (i + 1)) / xCount;
}
// charCounts is the histogram of letters
// permcount is the number of distinct perms of letters
StringBuilder perm = new StringBuilder();
for(int i = 0; i < letters.length(); i++) {
List<Character> sorted = new ArrayList<>(charCounts.keySet());
Collections.sort(sorted);
for(Character x : sorted) {
// suffixcount is the number of distinct perms that begin with x
Integer frequency = charCounts.get(x);
int suffixcount = permcount * frequency / (letters.length() - i);
if (rank <= suffixcount) {
perm.append(x);
permcount = suffixcount;
if(frequency == 1) {
charCounts.remove(x);
} else {
charCounts.put(x, frequency - 1);
}
break;
}
rank -= suffixcount;
}
}
return perm.toString();
}
See also n-th-permutation-algorithm-for-use-in-brute-force-bin-packaging-parallelization.

Project Euler #8, I don't understand where I'm going wrong

I'm working on project euler problem number eight, in which ive been supplied this ridiculously large number:
7316717653133062491922511967442657474235534919493496983520312774506326239578318016984801869478851843858615607891129494954595017379583319528532088055111254069874715852386305071569329096329522744304355766896648950445244523161731856403098711121722383113622298934233803081353362766142828064444866452387493035890729629049156044077239071381051585930796086670172427121883998797908792274921901699720888093776657273330010533678812202354218097512545405947522435258490771167055601360483958644670632441572215539753697817977846174064955149290862569321978468622482839722413756570560574902614079729686524145351004748216637048440319989000889524345065854122758866688116427171479924442928230863465674813919123162824586178664583591245665294765456828489128831426076900422421902267105562632111110937054421750694165896040807198403850962455444362981230987879927244284909188845801561660979191338754992005240636899125607176060588611646710940507754100225698315520005593572972571636269561882670428252483600823257530420752963450
and am supposed to "Find the thirteen adjacent digits in the 1000-digit number that have the greatest product." EG the product of the first four adjacent digits is 7 * 3 * 1 * 6.
My code is the following:
int main()
{
string num = /* ridiculously large number omitted */;
int greatestProduct = 0;
int product;
for (int i=0; i < num.length() -12; i++)
{
product = ((int) num[i] - 48);
for (int j=i+1; j<i+13; j++)
{
product = product * ((int) num[j] - 48);
if (greatestProduct <= product)
{
greatestProduct = product;
}
}
}
cout << greatestProduct << endl;
}
I keep getting 2091059712 as the answer which project euler informs me is wrong and I suspect its too large anyway. Any help would be appreciated.
EDIT: changed to unsigned long int and it worked. Thanks everyone!
In fact your solution is too small rather than too big. The answer is what was pointed out in the comments, that there is integer overflow, and the clue is in the fact that your solution is close to the largest possible value for an signed int: 2147483647. You need to use a different type to store the product.
Note that the answer below is still 'correct' in that your code does do this wrong, but it's not what is causing the wrong value. Try taking your (working) code to http://codereview.stackexchange.com if you would like the folks there to tell you what you could improve in your approach and your coding style.
Previous answer
You are checking for a new greatest product inside the inner loop instead of outside. This means that your maximum includes all strings of less or equal ton 13 digits, rather than only exactly 13.
This could make a difference if you are finding a string which has fewer than 13 digits which have a large product, but a 0 at either end. You shouldn't count this as the largest, but your code does. (I haven't checked if this does actually happen.)
for (int i=0; i < num.length() -12; i++)
{
product = ((int) num[i] - 48);
for (int j=i+1; j<i+13; j++)
{
product = product * ((int) num[j] - 48);
}
if (greatestProduct <= product)
{
greatestProduct = product;
}
}
9^13 ≈ 2.54e12 (maximal possible value, needs 42 bit to be represented exactly), which doesn't fit into signed int. You should use int64.
If you don't want to mess with BigNum libraries, you could just take logarithms of your digits (rejecting 0) and add them up. It amounts to the same comparison.
A faster way without internal loop, but works only where there isn't a 0 in the input:
long long greatest(string num)
{
if (num.length() < 13)
return 0;
// Find a product of first 13 numbers.
long long product = 1;
unsigned int i;
for (i=0; i<13; ++i) {
product *= (num[i]-'0');
}
long long greatest_product = product;
// move through the large number
for (i=0; i+13<num.length(); ++i) {
product = product/(num[i]-'0')*(num[i+13]-'0');
if (greatest_product < product)
greatest_product = product;
}
return greatest_product;
}
In order to make this work with inputs containing 0, split the input string into substrings:
int main()
{
string num = /* input value*/;
long long greatest_product = 0;
size_t start = -1;
// Iterate over substrings without zero
do {
++start;
size_t end = num.find('0', start);
long long product = greatest(num.substr(start, end-start));
if (greatest_product < product)
greatest_product = product;
start = end;
} while (start != string::npos);
cout << greatest_product << endl;
}
My functional programming solution
def product(number):
product_result = 1
for n in number:
product_result *= int(n)
return product_result
length = 13
indices = range(0, len(number) - 13 + 1)
values = indices
values = map(lambda index: {"index": index, "number": number}, values)
values = map(lambda value: value["number"][value["index"]:value["index"] + length], values)
values = map(product, values)
values = max(values)
print values
public static void main(String[] args) {
String val = "7316717653133062491922511967442657474235534919493496983520312774506326239578318016984801869478851843858615607891129494954595017379583319528532088055111254069874715852386305071569329096329522744304355766896648950445244523161731856403098711121722383113622298934233803081353362766142828064444866452387493035890729629049156044077239071381051585930796086670172427121883998797908792274921901699720888093776657273330010533678812202354218097512545405947522435258490771167055601360483958644670632441572215539753697817977846174064955149290862569321978468622482839722413756570560574902614079729686524145351004748216637048440319989000889524345065854122758866688116427171479924442928230863465674813919123162824586178664583591245665294765456828489128831426076900422421902267105562632111110937054421750694165896040807198403850962455444362981230987879927244284909188845801561660979191338754992005240636899125607176060588611646710940507754100225698315520005593572972571636269561882670428252483600823257530420752963450";
int Sum = 0;
String adjacent = null;
for (int i = 0; i < val.length()-13; i++) {
int total = 1;
for (int j = 0; j < 13; j++) {
total = total * Character.getNumericValue(val.charAt(i+j));
}
if(total > Sum){
Sum = total;
adjacent = val.substring(i, i+13);
}
}
System.out.println("Sum = " + Sum);
System.out.println("Adjsc = " + adjacent );
}
I had the same problem.
int product and int greatestproduct have maximum value it can store since they are 'int' type. They can only store values up to 2147483647.
Use 'long long' type instead of 'int'.
const thousandDigit =
`73167176531330624919225119674426574742355349194934
96983520312774506326239578318016984801869478851843
85861560789112949495459501737958331952853208805511
12540698747158523863050715693290963295227443043557
66896648950445244523161731856403098711121722383113
62229893423380308135336276614282806444486645238749
30358907296290491560440772390713810515859307960866
70172427121883998797908792274921901699720888093776
65727333001053367881220235421809751254540594752243
52584907711670556013604839586446706324415722155397
53697817977846174064955149290862569321978468622482
83972241375657056057490261407972968652414535100474
82166370484403199890008895243450658541227588666881
16427171479924442928230863465674813919123162824586
17866458359124566529476545682848912883142607690042
24219022671055626321111109370544217506941658960408
07198403850962455444362981230987879927244284909188
84580156166097919133875499200524063689912560717606
05886116467109405077541002256983155200055935729725
71636269561882670428252483600823257530420752963450`;
const productsOfAdjacentNths = num =>
[...thousandDigit].reduce((acc, _, idx) => {
const nthDigitAdjX = [...thousandDigit.substr(idx, num)].reduce(
(inAcc, inCur) => inCur * inAcc,
1
);
return acc.concat(nthDigitAdjX);
}, []);
console.log(Math.max(...productsOfAdjacentNths(13))); //5377010688
This is my O(n) approach
function findLargest(digits, n){
let largest = 0;
let j = 0;
let res = 1;
for(let i = 0; i< digits.length; i ++){
res = res * parseInt(digits[i]);
if(res == 0){
res = 1;
j = 0;
continue;
}
if(j === n-1){
if(res > largest)
largest = res;
res = res/parseInt(digits[i - j]);
j = j - 1;
}
j = j + 1;
}
return largest;
}
let val = "7316717653133062491922511967442657474235534919493496983520312774506326239578318016984801869478851843858615607891129494954595017379583319528532088055111254069874715852386305071569329096329522744304355766896648950445244523161731856403098711121722383113622298934233803081353362766142828064444866452387493035890729629049156044077239071381051585930796086670172427121883998797908792274921901699720888093776657273330010533678812202354218097512545405947522435258490771167055601360483958644670632441572215539753697817977846174064955149290862569321978468622482839722413756570560574902614079729686524145351004748216637048440319989000889524345065854122758866688116427171479924442928230863465674813919123162824586178664583591245665294765456828489128831426076900422421902267105562632111110937054421750694165896040807198403850962455444362981230987879927244284909188845801561660979191338754992005240636899125607176060588611646710940507754100225698315520005593572972571636269561882670428252483600823257530420752963450";
findLargest(val, 13);
Although above solutions are good, here is a python implementation which works perfectly:
def main():
num=7316717653133062491922511967442657474235534919493496983520312774506326239578318016984801869478851843858615607891129494954595017379583319528532088055111254069874715852386305071569329096329522744304355766896648950445244523161731856403098711121722383113622298934233803081353362766142828064444866452387493035890729629049156044077239071381051585930796086670172427121883998797908792274921901699720888093776657273330010533678812202354218097512545405947522435258490771167055601360483958644670632441572215539753697817977846174064955149290862569321978468622482839722413756570560574902614079729686524145351004748216637048440319989000889524345065854122758866688116427171479924442928230863465674813919123162824586178664583591245665294765456828489128831426076900422421902267105562632111110937054421750694165896040807198403850962455444362981230987879927244284909188845801561660979191338754992005240636899125607176060588611646710940507754100225698315520005593572972571636269561882670428252483600823257530420752963450
prod,maxprod=1,0
numtostr=str(num)
length=len(numtostr)
for i in range(1,length-13+1):
prod=1
for z in range(i,i+13):
prod=prod*int(numtostr[z-1:z])
if prod>maxprod:
maxprod=prod
print "Largest 13 digit product is %d" %(maxprod)
if __name__ == '__main__':
main()
static long q8(){
long max_product = 1;
long product = 1;
String n = "LONG_INPUT";
for(int i=0;i<13;i++){
max_product *= Integer.parseInt(n.charAt(i)+"");
}
product = max_product;
for(int i=1;i<n.length()-13;i++){
int denom = Integer.parseInt(n.charAt(i-1)+"");
if(denom!=0)
product = product/denom * Integer.parseInt(n.charAt(i+12)+"");
else
product = product(i,n);
max_product = (max_product>product)?max_product:product;
}
return max_product;
}
static long product(int index,String n){
long pro = 1;
for(int i=index;i<index+13;i++){
pro *= Integer.parseInt(n.charAt(i)+"");
}
return pro;
}
Try this:
{
DateTime BeganAt = new DateTime();
BeganAt = DateTime.Now;
Int64 result = 0;
string testNumber = "7316717653133062491922511967442657474235534919493496983520312774506326239578318016984801869478851843858615607891129494954595017379583319528532088055111254069874715852386305071569329096329522744304355766896648950445244523161731856403098711121722383113622298934233803081353362766142828064444866452387493035890729629049156044077239071381051585930796086670172427121883998797908792274921901699720888093776657273330010533678812202354218097512545405947522435258490771167055601360483958644670632441572215539753697817977846174064955149290862569321978468622482839722413756570560574902614079729686524145351004748216637048440319989000889524345065854122758866688116427171479924442928230863465674813919123162824586178664583591245665294765456828489128831426076900422421902267105562632111110937054421750694165896040807198403850962455444362981230987879927244284909188845801561660979191338754992005240636899125607176060588611646710940507754100225698315520005593572972571636269561882670428252483600823257530420752963450";
StringBuilder StringBuilder = new StringBuilder(13);
Int64 maxNumber = 0;
try
{
char[] numbers = testNumber.ToCharArray();
int tempCounter = 13;
for (int i = 0;i < numbers.Length;i++)
{
if(i < tempCounter)
{
StringBuilder.Append(numbers[i]);
}
else if (i == tempCounter)
{
if (maxNumber < Convert.ToInt64(StringBuilder.ToString()))
{
maxNumber = Convert.ToInt64(StringBuilder.ToString());
}
StringBuilder.Clear();
StringBuilder.Append(numbers[i]);
tempCounter = tempCounter + n;
}
}
result = maxNumber;
}
catch
{
throw;
}
DateTime EndedAt = new DateTime();
EndedAt = DateTime.Now;
TimeSpan TimeItTook = (EndedAt - BeganAt);
return Convert.ToString(result) + " - Time took to execute: " + Convert.ToString(TimeItTook.TotalMilliseconds);
}
long long int sum = 1,high=0;
for (int i = 0; i < 988; i++)
{
sum = sum*(arr[i] - 48);
for (int j = i + 1; j < i+13; j++)
{
sum = sum*(arr[j]-48);
}
if (sum >= high)
{
high = sum;
}
sum = 1;
}
My solution to above problem if someone is still watching this in 2018.Although there are lots of solution to this question here my solution pre-checks the individual 13 digits which have a 0 in them.As something multiplied with 0 is always 0 so we can remove this useless computation
int j = 0, k = 12;
long long int mult = 1;
long long int max = 0;
char *digits = /*Big number*/
while(k < 1000){
for (int i = j; i <= k; ++i)
{
/* code */
long long int val = digits[i] -'0';
/* check if any number in series contains 0 */
if(val == 0){
break;
}
mult = mult * val;
}
printf("mult is %lld\n",mult );
/* check for max value */
if(max < mult){
max = mult;
}
printf("the new max is %lld\n", max);
j += 1;
k += 1;
mult = 1;
printf("%d iteration finished\n", k);
}
printf("%lld\n", max);
You should use 'int64_t' at the place of 'int'
I have solve this problem using python 're' module
Finding all possible 13 digits number without having zeros (total 988 with zero and 283 without zero) then find the product of each of these digits and check for max
here i have used look ahead regex
Note: string must not contain any newline char
s = '731671765...'
import re
def product_13(d):
pro = 1
while d:
pro *= d % 10
d //= 10
return pro
pat = re.compile(r'(?=([1-9]{13}))')
all = map(int, re.findall(pat, s))
pro = -1
for i in all:
v = product_13(i)
if pro < v:
pro = v
print(pro)
**This is JavaScript solution.**
greatestProductOfAdjacentDigit = (givenNumber, noOfDigit) => {
stringNumberToNumbers = givenNumber => givenNumber.split('').map(each => parseInt(each, 10))
let numbers = mathematicalProblems.stringNumberToNumbers(givenNumber);
return numbers.map(function (each, ind, arr) {
return mathematicalProblems.productOfAll(arr.slice(ind, ind + noOfDigit));
}).reduce(function (accumulator, currentValue) {
return accumulator > currentValue ? accumulator : currentValue;
});
};
Testing
const givenNumber = '73167176531330624919225119674426574742355349' +
'194934969835203127745063262395783180169848018694788518438586' +
'156078911294949545950173795833195285320880551112540698747158' +
'523863050715693290963295227443043557668966489504452445231617' +
'318564030987111217223831136222989342338030813533627661428280' +
'644448664523874930358907296290491560440772390713810515859307' +
'960866701724271218839987979087922749219016997208880937766572' +
'733300105336788122023542180975125454059475224352584907711670' +
'556013604839586446706324415722155397536978179778461740649551' +
'492908625693219784686224828397224137565705605749026140797296' +
'865241453510047482166370484403199890008895243450658541227588' +
'666881164271714799244429282308634656748139191231628245861786' +
'645835912456652947654568284891288314260769004224219022671055' +
'626321111109370544217506941658960408071984038509624554443629' +
'812309878799272442849091888458015616609791913387549920052406' +
'368991256071760605886116467109405077541002256983155200055935' +
'72972571636269561882670428252483600823257530420752963450';
console.log(greatestProductOfAdjacentDigit(givenNumber, 4)); //5832
console.log(greatestProductOfAdjacentDigit(givenNumber, 13)); //23514624000
My 2 cents ... Javascript
Largest_product_in_series_13 = g => {
return [...g.matchAll(/(?=([1-9]{13}))/g)]
.reduce((a,c)=>(p=eval(c[1].split``.join`*`),p>a?p:a),0)
}
First it matches all 13 digit series, then it reduces to the biggest product.
console.log(Largest_product_in_series_13(`7316717653133062491922....
> 23514624000
start: 14.292ms
I solved it using ruby. if
x = "7316717653133062491922511967442657474235534919493496983520312774506326239578318016984801869478851843858615607891129494954595017379583319528532088055111254069874715852386305071569329096329522744304355766896648950445244523161731856403098711121722383113622298934233803081353362766142828064444866452387493035890729629049156044077239071381051585930796086670172427121883998797908792274921901699720888093776657273330010533678812202354218097512545405947522435258490771167055601360483958644670632441572215539753697817977846174064955149290862569321978468622482839722413756570560574902614079729686524145351004748216637048440319989000889524345065854122758866688116427171479924442928230863465674813919123162824586178664583591245665294765456828489128831426076900422421902267105562632111110937054421750694165896040807198403850962455444362981230987879927244284909188845801561660979191338754992005240636899125607176060588611646710940507754100225698315520005593572972571636269561882670428252483600823257530420752963450"
then used below logic to solve the problem
def print_lps(x)
p = 1
0.upto(x.length-13) do |i|
j = i
xy = 1
while j < i+13 do
xy *= x[j].to_i
j += 1
end
p = xy if xy > p
end
puts p
end
print_lps(x) # 23514624000
I solve the problem using this approach
1.Run two loops first outer loop which iterate over numbers in the string.
2.Inner loop reach to next 13 numbers afterwards and store its product in a variable
3.As inner loop ends we only use maximum value.(that what we need) :>
Have a look at my code in C++
#include <bits/stdc++.h>
using namespace std;
int main()
{
string s="//thestring is there";
long long unsigned mainans=1,ans=1; //initialize the value of mainans and ans to 1 (not 0 as product also become 0)
for(int i=0;i<s.length()-13;i++) //run the loop from 0 upto 13 minus string length
{
ans=1;
for(int j=i;j<i+13;j++) //now from that particular digit we check 13 digits afterwards it
{
int m=s[j]-'0'; //convert the number from string to integer
ans*=m; //taking product in every interation for 13 digits
}
mainans=max(mainans,ans); //now taking only max value because that what we need
}
cout<<mainans;
return 0;
}
This will find the answer in O(n) time and it handles zero. Written in Dart.
/**
* Main function
*
* Find the thirteen adjacent digits in the 1000-digit number that have the greatest product.
* What is the value of this product?
*
*/
const String DIGITS = "73167176531330624919225119674426574742355349194934"
"96983520312774506326239578318016984801869478851843"
"85861560789112949495459501737958331952853208805511"
"12540698747158523863050715693290963295227443043557"
"66896648950445244523161731856403098711121722383113"
"62229893423380308135336276614282806444486645238749"
"30358907296290491560440772390713810515859307960866"
"70172427121883998797908792274921901699720888093776"
"65727333001053367881220235421809751254540594752243"
"52584907711670556013604839586446706324415722155397"
"53697817977846174064955149290862569321978468622482"
"83972241375657056057490261407972968652414535100474"
"82166370484403199890008895243450658541227588666881"
"16427171479924442928230863465674813919123162824586"
"17866458359124566529476545682848912883142607690042"
"24219022671055626321111109370544217506941658960408"
"07198403850962455444362981230987879927244284909188"
"84580156166097919133875499200524063689912560717606"
"05886116467109405077541002256983155200055935729725"
"71636269561882670428252483600823257530420752963450";
main(List<String> args) {
const int MAX_DIGITS = 13;
int len = DIGITS.length;
int digits = 0;
int largest = 0;
int current = 0;
int index = 0;
while (index < len) {
int value = int.parse(DIGITS[index]);
// if we get a zero then rebuild the MAX_DIGITS consecutive digits
if (value == 0) {
current = 0;
digits = 0;
} else {
// Multiply consecutive digits up to target set
if (digits < MAX_DIGITS) {
if (current == 0) {
current = value;
} else
current *= value;
digits++;
} else {
int divisor = int.parse(DIGITS[index - MAX_DIGITS]);
if (current == 0) {
current = value;
} else {
current = (current ~/ divisor);
current *= value;
}
}
if (current > largest) {
largest = current;
}
}
index++;
}
print('Num $largest');
}