C: How to convert a string of ints into actual ints and store them in an array?
Date : March 29 2020, 07:55 AM
hop of those help? Robust string processing in C is never simple. Here's a procedure that popped immediately to mind for me. Use strtok() to break the string into individual tokens, then convert each token to an integer value using strtol(). #include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
/**
* Convert a space-delimited string of integers to an array of corresponding
* integer values.
*
* @param str [in] -- input string
* @param arr [in] -- destination array
* @param arrSize [in] -- max number of elements in destination array
* @param count [out] -- number of elements assigned to destination array
*/
void stringToIntList(char *str, int *arr, size_t arrSize, size_t *count)
{
/**
* The token variable holds the next token read from the input string
*/
char *token;
/**
* Make a copy of the input string since we are going to use strtok(),
* which modifies its input.
*/
char *localStr = malloc(strlen(str) + 1);
if (!localStr)
{
/**
* malloc() failed; we're going to treat this as a fatal error
*/
exit(-1);
}
strcpy(localStr, str);
/**
* Initialize our output
*/
*count = 0;
/**
* Retrieve the first token from the input string.
*/
token = strtok(localStr, " ");
while (token && *count < arrSize)
{
char *chk;
int val = (int) strtol(token, &chk, 10);
if (isspace(*chk) || *chk == 0)
{
arr[(*count)++] = val;
}
else
{
printf("\"%s\" is not a valid integer\n", token);
}
/**
* Get the next token
*/
token = strtok(NULL, " ");
}
/**
* We're done with the dynamic buffer at this point.
*/
free(localStr);
}
int main(void)
{
int values[5];
char *str = "14 22 33 48 5q";
size_t converted;
stringToIntList(str, values, sizeof values / sizeof values[0], &converted);
if (converted > 0)
{
size_t i;
printf("Converted %lu items from \"%s\":\n", (unsigned long) converted, str);
for (i = 0; i < converted; i++)
printf("arr[%lu] = %d\n", (unsigned long) i, arr[i]);
}
else
{
printf("Could not convert any of \"%s\" to equivalent integer values\n", str);
}
return 0;
}
|
How to check if calculations are within ints higher and lower ranges
Date : March 29 2020, 07:55 AM
I wish did fix the issue. Convert one of the arguments to a long first, then the entire calculation will use 64-bit integers. There's no danger of overflow so long as your original arguments remain typed as int: long.MaxValue has more than twice the magnitude of int.MaxValue * int.MaxValue, similarly with long.MinValue and int.MinValue * int.MaxValue. long longVal1 = (long)val1;
if (funcType == "Mul")
return (longVal1 * val2) <= int.MaxValue && (longVal1 * val2) >= int.MinValue;
if (funcType == "Add")
return (longVal1 + val2) <= int.MaxValue && (longVal1 + val2) >= int.MinValue;
if (funcType == "Sub")
return (longVal1 - val2) <= int.MaxValue && (longVal1 - val2) >= int.MinValue;
if (funcType == "Div")
return (longVal1 / val2) <= int.MaxValue && (longVal1 / val2) >= int.MinValue;
|
In Java, map visible spectrum to RGB based on calculated integer (higher ints should be closer to ultraviolet, lower int
Date : November 04 2020, 04:00 PM
will be helpful for those in need You should be looking at using either "HSL" or "HSB" (aka "HSV") colour space, where the "H" in both stands for "hue". Hue is typically measured as an angle in degrees, with 0 degrees representing red, 120 for green, 240 for blue, although some libraries use the range 0..1 Keepping "S" and "B" constant and varying "H" linearly from the bottom of the range to the top will produce the typical "rainbow" of colours. setColor(Color.getHSBColor(spectrumValue, 1.0, 1.0));
|
Finding craters [descending/ ascending ints] in a python list of ints
Tag : python , By : Bjørn Lyngwa
Date : March 29 2020, 07:55 AM
hop of those help? Presuming your expected output is wrong which it seems to be, all you want to do is go until you find an element >= to the start of the chain and catch chains that only contain a single element: def craters(lst):
it = iter(lst)
# get start of first chain
first = next(it)
tmp = [first]
# iterate over the remaining
for ele in it:
# >= ends chain
if ele >= first:
# if equal, add it and call
# next(it) to set the next first element.
if ele == first:
tmp.append(ele)
yield tmp
first = next(it)
tmp = [first]
# else yield the group if it has > 1 element.
# if it has 1 element it is not a descending start sequecne
else:
if len(tmp) > 1:
yield tmp
tmp = [ele]
first = ele
else:
tmp.append(ele)
if len(tmp) > 1: # catch single element last
yield tmp
In [5]: ok_list = [12, 4, 7, 4, 2, 4, 5, 6, 5, 12, 21, 23,
...: 24, 26, 25, 22, 10, 9, 8, 6, 9, 10, 11, 13, 12, 14,
...: 17, 27, 28, 19, 17, 19, 21, 19, 12, 23, 25, 27]
In [6]: problematic = [12, 4, 7, 4, 2, 4, 5, 6, 5, 12, 21, 23,
...: 24, 26, 25, 22, 10, 9, 8, 6, 9, 10, 11, 13, 12, 14,
...: 17, 27, 19, 25, 19, 12, 23, 25, 27]
In [7]: ex_ok = [[12, 4, 7, 4, 2, 4, 5, 6, 5, 12],
...: [26, 25, 22, 10, 9, 8, 6, 9, 10, 11, 13, 12, 14, 17],
...: [28, 19, 17, 19, 21, 19, 12, 23, 25, 27]]
In [8]: ex_p = [[12,4, 7, 4, 2, 4, 5, 6, 5, 12],
...: [26, 25, 22, 10, 9, 8, 6, 9, 10, 11, 13, 12, 14, 17],
...: [27, 19, 25, 19, 12, 23, 25, 27]]
In [9]: print(list(craters(problematic)) == ex_p)
True
In [10]: print(list(craters(ok_list)) == ex_ok)
True
In [11]: print(list(craters([12, 4, 7, 4, 2, 4, 5, 6, 5, 12, 21, 10, 9, 8, 6, 9, 10])))
[[12, 4, 7, 4, 2, 4, 5, 6, 5, 12], [21, 10, 9, 8, 6, 9, 10]]
In [12]: list(craters([1, 2, 3, 4, 5, 6, 5, 4, 3, 4, 5, 6, 7, 8, 9]))
Out[13]: [[6, 5, 4, 3, 4, 5, 6]]
|
Function speed improvement: Convert ints to list of 32bit ints
Date : March 29 2020, 07:55 AM
I think the issue was by ths following , I'm looking for speedy alternatives to my function. the goal is to make a list of 32 bit integers based of any length integers. The length is explicitly given in a tuple of (value, bitlength). This is part of a bit-banging procedure for a asynchronous interface which takes 4 32 bit integers per bus transaction. , The best I could come up with so far is a 25% speed-up from functools import reduce
intMask = 0xffffffff
def f(x,y):
return (x[0] << y[1]) + y[0], x[1] + y[1]
def jens(input):
n, length = reduce( f , input, (0,0) )
remainderBits = length % 32
intBits = length - remainderBits
remainder = ((n & intMask) << (32 - remainderBits)) >> (32 - remainderBits)
n >>= remainderBits
ints = [n & (intMask << i) for i in range(intBits-32, -32, -32)]
return ints, remainderBits, remainder
print([hex(x) for x in jens([(0,128),(1,12),(0,32)])[0]])
Fastest to slowest execution speeds using Python 3.6.5
(1,000 executions, best of 3 repetitions)
jens : 0.004151 secs, rel speed 1.00x, 0.00% slower
First snippet : 0.005259 secs, rel speed 1.27x, 26.70% slower
Second snippet : 0.008328 secs, rel speed 2.01x, 100.64% slower
|